Python QWebEngineView and QWebChannel
Solved
QtWebEngine
-
Hi, I can't get a minimal implementation of QWebChannel communication between a python script and QWebEngineView to work, what am I missing here?
import sys from PySide6.QtCore import QObject from PySide6.QtWebChannel import QWebChannel from PySide6.QtWebEngineWidgets import QWebEngineView from PySide6.QtWidgets import QApplication class Py(QObject): def msg(self, msg): print("msg: ", msg) if __name__ == "__main__": app = QApplication(sys.argv) web = QWebEngineView() channel = QWebChannel(web) py = Py(app) channel.registerObject("py", py) web.page().setWebChannel(channel) web.setHtml(''' <html> <head> <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script> <script> var py channel = new QWebChannel(qt.webChannelTransport, function(channel) { py = channel.objects.py }) </script> </head> <body> Demo<br> <button onclick="py.msg('button clicked')">click me</button> </body> </html> ''') web.show() app.exec()
Thanks!
-
@TRIAEIOU
Solved, I was missing @Slot:import sys, json from PySide6.QtCore import QObject, Slot from PySide6.QtWebChannel import QWebChannel from PySide6.QtWebEngineWidgets import QWebEngineView from PySide6.QtWidgets import QApplication class Py(QObject): @Slot(str, result=str) def msg(self, msg): print("py.msg: ", msg) return json.dumps("clicked") if __name__ == "__main__": app = QApplication(sys.argv) web = QWebEngineView() channel = QWebChannel(web) py = Py(app) channel.registerObject("py", py) web.page().setWebChannel(channel) web.setHtml(''' <html> <head> <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script> <script type="text/javascript"> var pymsg new QWebChannel(qt.webChannelTransport, function(channel) { pymsg = function (msg, cb = Function.prototype) { channel.objects.py.msg(msg, (res) => cb(JSON.parse(res))) return false } }) </script> </head> <body> <button onclick="pymsg('button clicked', (res) => {alert(res)})">click me</button> </body> </html> ''') web.show() app.exec()
-