如何使用QWebChannel从python接收数据到js?
问题内容:
我正在尝试让我的PyQt应用程序与JS通信,但无法从python获取值。我在python端有两个插槽来获取和打印数据。在示例中,将一个int从JS传递给python,python将其加5并将其传递回去,然后JS调用另一个插槽以打印新值。
var backend = null;
var x = 15;
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
backend.getRef(x, function(pyval){
backend.printRef(pyval)
});
});
@pyqtSlot(int)
def getRef(self, x):
print('inside getRef', x)
return x + 5
@pyqtSlot(int)
def printRef(self, ref):
print('inside printRef', ref)
输出:
inside getRef 15
Could not convert argument QJsonValue(null) to target type int .
预期:
inside getRef 15
inside printRef 20
我不知道为什么返回的值为空。我如何将pyval存储到js端的变量中以供以后使用?
问题答案:
在C
++中,这样一个方法可以返回一个值,该方法必须声明为,Q_INVOKABLE
并且result
在@pyqtSlot
装饰器中使用PyQt中的等效方法:
├── index.html
└── main.py
main.py
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, QtWebChannel
class Backend(QtCore.QObject):
@QtCore.pyqtSlot(int, **result=int** )
def getRef(self, x):
print("inside getRef", x)
return x + 5
@QtCore.pyqtSlot(int)
def printRef(self, ref):
print("inside printRef", ref)
if __name__ == "__main__":
import os
import sys
app = QtWidgets.QApplication(sys.argv)
backend = Backend()
view = QtWebEngineWidgets.QWebEngineView()
channel = QtWebChannel.QWebChannel()
view.page().setWebChannel(channel)
channel.registerObject("backend", backend)
current_dir = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(current_dir, "index.html")
url = QtCore.QUrl.fromLocalFile(filename)
view.load(url)
view.resize(640, 480)
view.show()
sys.exit(app.exec_())
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script type="text/javascript">
var backend = null;
var x = 5;
window.onload = function()
{
new QWebChannel(qt.webChannelTransport, function(channel) {
backend = channel.objects.backend;
backend.getRef(x, function(pyval) {
backend.printRef(pyval);
});
});
}
</script>
</head>
</html>
更新:
通常,QtWebChannel只能传输可以从Qt端转换为QJsonObject的信息,而可以从javascript端传输可以转换为JSON的数据。
因此,有一些特殊情况:
- 整型
- 浮动
- 力量
-
list :如果支持发送和接收列表,但支持元素(如数字和字符串)以及字典和其他支持先前基本类型的列表,则可以发送和接收列表。
class Backend(QtCore.QObject):
@QtCore.pyqtSlot(result=list)
def return_list(self):
return [0.0, 1.5, ‘Hello’, [‘Stack’, 5.0], {‘a’: {‘b’: ‘c’}}]@QtCore.pyqtSlot(list) def print_list(self, l): print(l)
backend = channel.objects.backend;
backend.return_list(function(pyval) {
backend.print_list(pyval);
});
输出:
[0.0, 1.5, 'Hello', ['Stack', 5.0], {'a': {'b': 'c'}}]
-
字典 :
class Backend(QtCore.QObject):
@QtCore.pyqtSlot(result=”QJsonObject”)
def return_dict(self):
return {“a”: 1.5, “b”: {“c”: 2}, “d”: [1, “3”, “4”]}@QtCore.pyqtSlot("QJsonObject") def print_dict(self, ref): print(ref)
backend = channel.objects.backend;
backend.return_dict(function(pyval) {
backend.print_dict(pyval);
});
输出:
{'a': <PyQt5.QtCore.QJsonValue object at 0x7f3841d50150>, 'b': <PyQt5.QtCore.QJsonValue object at 0x7f3841d501d0>, 'd': <PyQt5.QtCore.QJsonValue object at 0x7f3841d50250>}
如您所见,返回了QJsonValue,因此获取信息可能很繁琐,因此在此解决方法是将它们打包在一个列表中:
class Backend(QtCore.QObject):
@QtCore.pyqtSlot(result=list)
def return_list(self):
d = {"a": 1.5, "b": {"c": 2}, "d": [1, "3", "4"]}
return [d]
@QtCore.pyqtSlot(list)
def print_list(self, ref):
d, *_ = ref
print(d)
backend = channel.objects.backend;
backend.return_list(function(pyval) {
backend.print_list(pyval);
});
输出:
{'a': 1.5, 'b': {'c': 2.0}, 'd': [1.0, '3', '4']}
UPDATE2:
传递信息的一种通用方法是使用JSON,即转换python或js对象,分别使用json.dumps()
和将其转换为字符串JSON.stringify()
,然后发送;当以python或js格式接收时,必须分别使用json.loads()
和转换字符串JSON.parse()
:
class Backend(QtCore.QObject):
@QtCore.pyqtSlot(str, result=str)
def getRef(self, o):
print("inside getRef", o)
py_obj = json.loads(o)
py_obj["c"] = ("Hello", "from", "Python")
return json.dumps(py_obj)
@QtCore.pyqtSlot(str)
def printRef(self, o):
py_obj = json.loads(o)
print("inside printRef", py_obj)
var backend = null;
window.onload = function()
{
new QWebChannel(qt.webChannelTransport, function(channel) {
backend = channel.objects.backend;
var x = {a: "1000", b: ["Hello", "From", "JS"]}
backend.getRef(JSON.stringify(x), function(y) {
js_obj = JSON.parse(y);
js_obj["f"] = false;
backend.printRef(JSON.stringify(js_obj));
});
});
}
inside getRef {"a":"1000","b":["Hello","From","JS"]}
inside printRef {'a': '1000', 'b': ['Hello', 'From', 'JS'], 'c': ['Hello', 'from', 'Python'], 'f': False}