4

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?

2
  • def printRefisnt returning anything. Commented Oct 2, 2019 at 23:10
  • There isn't any data that's supposed to be passes back from printRef. It simply prints the value received from getRef. The problem is getRef is not properly returing the value x+5 to JS so it can then be printed by printRef. Commented Oct 2, 2019 at 23:15

1 Answer 1

13

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}
Sign up to request clarification or add additional context in comments.

4 Comments

Is this the case with dict and list structures as well?
@eyllanesc Not sure if this question is out of scope here but I can still ask it... how would you send a dictionary from python->js? If I've got sendDict = pyqtSignal(dict) and then I do talkie.sendDict.emit({"a":10}) I'll get null in the js side. On the other hand, when dealing with simple types such as int, float, str, bool, list the values in js-side are received ok... Only having trouble with datatypes such as list, set, tuple, object, ...
@BPL I have added a more generic method which should generally allow sending any object that can be converted to JSON.
@eyllanesc Hehe, cool, when I'd asked you the same question few hours ago I'd reached a similar conclusion than you, at that time I was concerned about the possible overhead of encoding/decoding... I've been using it for a while and it seems is good enough. That said, thank you very much to confirm this is an idiomatic way to send these datatypes... I've already upvoted you ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.