如何讓PyQt5中QWebEngineView與JavaScript互動
阿新 • • 發佈:2020-10-22
準備工作
開發環境
- Python 3.8.1
- Windows 10
安裝依賴
pip install PyQt5 pip install PyQtWebEngine
Python端
1.使用QWebChannel的registerObject("JsBridge名","JsBridge")方法註冊回撥
- JsBridge名:在JavaScript中呼叫時使用的物件名稱
- JsBridge:被JavaScript呼叫的Python物件
2.JsBridge 物件
- 入參
@QtCore.pyqtSlot(str) def log(self,message): print(message)
- 出參
@QtCore.pyqtSlot(result=str) def getName(self): return "hello"
- 出入參
@QtCore.pyqtSlot(str,result=str) def test(self,message): print(message) return "ok"
JavaScript端
在Html的<head>中新增
<script src='qrc:///qtwebchannel/qwebchannel.js'></script>
呼叫
new QWebChannel(qt.webChannelTransport,function(channel) { channel.objects.pythonBridge.test("hello",function(arg) { console.log("Python message: " + arg); alert(arg); }); });
除錯(Chrome DevTools)
- 配置環境變數:QTWEBENGINE_REMOTE_DEBUGGING = port
- 使用Chromium核心的瀏覽器開啟地址:http://127.0.0.1:port
- 使用PyCharm中可以在執行配置(Run/Debug Configurations)中的Environment variables中新增環境變數,用;號分隔,然後可以直接執行。
Demo
Python
1.JsBridge
from PyQt5 import QtCore class JsBridge(QtCore.QObject): @QtCore.pyqtSlot(str,result=str) def test(self,message): print(message) return "ok"
2.Application
from PyQt5 import QtCore from PyQt5 import QtWebEngineWidgets from PyQt5.QtCore import QDir from PyQt5.QtWebChannel import QWebChannel from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import * class TestWindow(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
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"> <title>Test</title> <script src='qrc:///qtwebchannel/qwebchannel.js'></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> </head> <body> <button id="test">test</button> </body> <script> $(document).ready(function() { new QWebChannel(qt.webChannelTransport,function(channel) { $('#test').on('click',function() { channel.objects.pythonBridge.test("hello",function(arg) { console.log("Python message: " + arg); alert(arg); }); }); }); }); </script> </html>
本文作者: liaoheng
本文連結: https://liaoheng.me/2019/12/23/PyQt5-QWebEngineView與JavaScript互動/
以上就是如何讓PyQt5中QWebEngineView與JavaScript互動的詳細內容,更多關於QWebEngineView與JavaScript互動的資料請關注我們其它相關文章!