问题
I'm trying to get my PyQt application to communicate with the JS but am unable to get values from python. I have two slots on the python side to get and print data. In the example a int is passed from JS to python, python adds 5 to it and passes it back, then JS calls the other slot to print the new value.
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)
Output:
inside getRef 15
Could not convert argument QJsonValue(null) to target type int .
Expected:
inside getRef 15
inside printRef 20
I can't figure out why the returned value is null. How would I store that pyval into a variable on the js side to be used later?
回答1:
In C++ so that a method can return a value it must be declared as Q_INVOKABLE
and the equivalent in PyQt is to use result
in the @pyqtSlot
decorator:
├── 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>
Update:
In general, QtWebChannel can only transport information that can be converted into QJsonObject from the Qt side, and from the javascript side those data that can be converted into JSON.
So there are particular cases:
- int
- float
- str
- list: If it is supported to send and receive lists but of elements such as numbers and strings, and also dictionary and other lists that support the previous basic types.
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);
});
Output:
[0.0, 1.5, 'Hello', ['Stack', 5.0], {'a': {'b': 'c'}}]
- dict:
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);
});
Output:
{'a': <PyQt5.QtCore.QJsonValue object at 0x7f3841d50150>, 'b': <PyQt5.QtCore.QJsonValue object at 0x7f3841d501d0>, 'd': <PyQt5.QtCore.QJsonValue object at 0x7f3841d50250>}
As you can see, QJsonValue is returned so it can be tedious to obtain the information, so in this the workaround is to package them in a list:
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);
});
Output:
{'a': 1.5, 'b': {'c': 2.0}, 'd': [1.0, '3', '4']}
UPDATE2:
A generic way of transmitting information is to use JSON, that is, convert the python or js object and convert it to string using json.dumps()
and JSON.stringify()
, respectively, and send it; when received in python or js the string must be converted using json.loads()
and JSON.parse()
, respectively:
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}
来源:https://stackoverflow.com/questions/58210400/how-to-receive-data-from-python-to-js-using-qwebchannel