如何让PyQt5中QWebEngineView与JavaScript交互
准备工作
开发环境
- Python3.8.1
- Windows10
安装依赖
pipinstallPyQt5 pipinstallPyQtWebEngine
Python端
1.使用QWebChannel的registerObject("JsBridge名","JsBridge")方法注册回调
- JsBridge名:在JavaScript中调用时使用的对象名称
- JsBridge:被JavaScript调用的Python对象
2.JsBridge对象
- 入参
@QtCore.pyqtSlot(str) deflog(self,message): print(message)
- 出参
@QtCore.pyqtSlot(result=str) defgetName(self): return"hello"
- 出入参
@QtCore.pyqtSlot(str,result=str) deftest(self,message): print(message) return"ok"
JavaScript端
在Html的
中添加调用
newQWebChannel(qt.webChannelTransport,function(channel){ channel.objects.pythonBridge.test("hello",function(arg){ console.log("Pythonmessage:"+arg); alert(arg); }); });
调试(ChromeDevTools)
- 配置环境变量:QTWEBENGINE_REMOTE_DEBUGGING=port
- 使用Chromium内核的浏览器打开地址:http://127.0.0.1:port
- 使用PyCharm中可以在运行配置(Run/DebugConfigurations)中的Environmentvariables中添加环境变量,用;号分隔,然后可以直接运行。
Demo
Python
1.JsBridge
fromPyQt5importQtCore classJsBridge(QtCore.QObject): @QtCore.pyqtSlot(str,result=str) deftest(self,message): print(message) return"ok"
2.Application
fromPyQt5importQtCore fromPyQt5importQtWebEngineWidgets fromPyQt5.QtCoreimportQDir fromPyQt5.QtWebChannelimportQWebChannel fromPyQt5.QtWebEngineWidgetsimportQWebEngineView fromPyQt5.QtWidgetsimport* classTestWindow(QMainWindow): def__init__(self): super().__init__() self.webView=QWebEngineView() self.webView.settings().setAttribute( QtWebEngineWidgets.QWebEngineSettings.JavascriptEnabled,True) channel=QWebChannel(self.webView.page()) self.webView.page().setWebChannel(channel) self.python_bridge=JsBridge(None) channel.registerObject("pythonBridge",self.python_bridge) layout=QVBoxLayout() layout.addWidget(self.webView) widget=QWidget() widget.setLayout(layout) self.setCentralWidget(widget) self.resize(900,600) self.setWindowTitle('Test') qr=self.frameGeometry() cp=QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) self.show() html_path=QtCore.QUrl.fromLocalFile(QDir.currentPath()+"/assets/index.html") self.webView.load(html_path) if__name__=='__main__': app=QApplication(sys.argv) m=TestWindow() sys.exit(app.exec_())
JavaScript
index.html
Test test
本文作者:liaoheng
本文链接:https://liaoheng.me/2019/12/23/PyQt5-QWebEngineView与JavaScript交互/
以上就是如何让PyQt5中QWebEngineView与JavaScript交互的详细内容,更多关于QWebEngineView与JavaScript交互的资料请关注毛票票其它相关文章!