准备工作
开发环境
- Python 3.8.1
- Windows 10
安装依赖
1 | pip install PyQt5 |
Python端
使用
QWebChannel
的registerObject("JsBridge名","JsBridge")
方法注册回调JsBridge名
:在JavaScript中调用时使用的对象名称JsBridge
:被JavaScript调用的Python对象
JsBridge
对象- 入参
1
2
3
def log(self, message):
print(message)- 出参
1
2
3
def getName(self):
return "hello"- 出入参
1
2
3
4
def test(self, message):
print(message)
return "ok"
JavaScript端
在Html的
<head>
中添加1
<script src='qrc:///qtwebchannel/qwebchannel.js'></script>
调用
1
2
3
4
5
6new 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
JsBridge
1
2
3
4
5
6
7from PyQt5 import QtCore
class JsBridge(QtCore.QObject):
def test(self, message):
print(message)
return "ok"Application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38from 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
1 |
|