How can I access Python code from JavaScript in PyQT 5.7?

I used to do it by attaching an object"js_interface", self.jsi)

In 5.7 I do:

But I understandibly get a JavaScript error when I try to access exposed functions:

js: Uncaught ReferenceError: js_interface is not defined

Googling around I found that I should use qwebchannel.js, but I couldn't find the file or instructions on how to use it anywhere (there was some info, but only in some examples provided when installing QT, not PyQT).



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

<script src="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):
    def test(self):
        print('call received')

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

JS code that interacts with the web channel:

new QWebChannel(qt.webChannelTransport, function (channel) {
    window.handler = channel.objects.handler;

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.


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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.