Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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).

like image 803
zamarov Avatar asked Jun 07 '26 05:06

zamarov


1 Answers

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):
    @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:

new QWebChannel(qt.webChannelTransport, function (channel) {
    window.handler = channel.objects.handler;
    window.handler.test();
});
like image 147
xuhcc Avatar answered Jun 10 '26 19:06

xuhcc