我正在尝试让我的 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
,PyQt 中的等效项是在@pyqtSlot
装饰器中使用result
:
├── 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_())
索引.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 的数据。
所以有特殊情况:
- 国际
- 浮
- str
- 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,即分别使用json.dumps()
和JSON.stringify()
转换 python 或 js 对象并将其转换为字符串,然后发送;在 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}