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?
In C++ so that a method can return a value it must be declared as
Q_INVOKABLEand the equivalent in PyQt is to useresultin the@pyqtSlotdecorator:main.py
index.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:
Output:
Output:
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:
Output:
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()andJSON.stringify(), respectively, and send it; when received in python or js the string must be converted usingjson.loads()andJSON.parse(), respectively: