Skip to content Skip to sidebar Skip to footer

How Can I Access Python Code From Javascript In Pyqt 5.7?

I used to do it by attaching an object self.page().mainFrame().addToJavaScriptWindowObject('js_interface', self.jsi) In 5.7 I do: self.page().setWebChannel(self.jsi) But I unders

Solution 1:

You can include qwebchannel.js into html page using the script tag:

<scriptsrc="qrc:///qtwebchannel/qwebchannel.js"></script>

Then, create a web channel on the python side:

from PyQt5.QtCore import QObject, pyqtSlot
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView

class CallHandler(QObject):
    @pyqtSlot()
    def test(self):
        print('call received')

view = QWebEngineView()
channel = QWebChannel()
handler = CallHandler()
channel.registerObject('handler', handler)
view.page().setWebChannel(channel)

JS code that interacts with the web channel:

newQWebChannel(qt.webChannelTransport, function (channel) {
    window.handler = channel.objects.handler;
    window.handler.test();
});

Solution 2:

Take a look at this page. It contains a useful example (in c++ but easily translatable into python).

First of all, you have to use a websocket to communicate from html to your app and viceversa.

Then you can set up your QWebChannel.

Solution 3:

I think it's big drawback, JS cannot directly communicate with Python in PyQT5.9+ like it used to with "addToJavaScriptWindowObject" command. And using websockets... what if Firewall is heavy and all ports blocked.

I guess I will rely on simple callback (long pooling type from Python to JS checking for changes/commands) method and no QTWebChannel usage.

Post a Comment for "How Can I Access Python Code From Javascript In Pyqt 5.7?"