PyQt5.9 Html与本地代码交互实例
在PyQt5.9中, 应用QWebEngineView和QWebChannel技术, 可以进行HTML与本地代码进行交互.
要点:
- 创建交互对象, 基于QObject, 定义信息槽
- 创建QWebChannel, 在channel中注册交互对象
- 设置页面WebChannel
- 定义网页
-
- 在网页中包含qwebchannel.js
- 在DomReady时, 创建js QWebChannel, 连接到本地对象
实例:
一. 创建Html文件
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script type="text/javascript" src="qwebchannel.js"></script> <title>QWebChannel测试</title> <script> window.onload = function () { new QWebChannel(qt.webChannelTransport, function (channel) { window.pyjs = channel.objects.pyjs; alert(pyjs.myHello()) }); } </script> </head> <body> </body> </html>
二. 创建Python代码
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QObject, pyqtSlot, QUrl from PyQt5.QtWebChannel import QWebChannel from PyQt5.QtWebEngineWidgets import QWebEngineView class CallHandler(QObject): @pyqtSlot(result=str) def myHello(self): print('call received') return 'hello, Python' if __name__ == '__main__': app = QApplication(sys.argv) view = QWebEngineView() channel = QWebChannel() handler = CallHandler() channel.registerObject('pyjs', handler) view.page().setWebChannel(channel) url_string = "file:///D:/qt5/201709/webengine/test.html" view.load(QUrl(url_string)) view.show() sys.exit(app.exec_())
问题:
在PyQt5.9中, QWebEngineView响应调用pyqtSlot时, 没有返回值, 返回null. 没有查到相应文档