我正在尝试,使用 Qt 类 QWebEngineView
, 和 QWebChannel
在 HTML 页面和 Python 脚本之间建立简单的连接。目标只是执行 foo()
当标题 <h2>
被点击。
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
html = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script>
var backend;
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
});
document.getElementById("header").addEventListener("click", function(){
backend.foo();
});
</script>
</head>
<body> <h2 id="header">Header.</h2> </body>
</html>
'''
class HelloWorldHtmlApp(QWebEngineView):
def __init__(self):
super().__init__()
# setup a page with my html
my_page = QWebEnginePage(self)
my_page.setHtml(html)
self.setPage(my_page)
# setup channel
self.channel = QWebChannel()
self.channel.registerObject('backend', self)
self.page().setWebChannel(self.channel)
self.show()
@pyqtSlot()
def foo(self):
print('bar')
if __name__ == "__main__":
app = QApplication.instance() or QApplication(sys.argv)
view = HelloWorldHtmlApp()
view.show()
app.exec_()
问题似乎是变量 backend
在 QWebChannel
之外不可见构造函数。我试着做 backend
widnow
的属性使其成为全局,但它没有用。
最佳答案
问题不是可见性而是与点击事件的连接,文件的上传是从上到下所以你试图在标题还不存在的时候连接,解决办法是重写HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
</head>
<body> <h2 id="header">Header.</h2> </body>
<script>
var backend;
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
});
document.getElementById("header").addEventListener("click", function(){
backend.foo();
});
</script>
</html>
关于python - PyQt QtWebChannel : calling Python function from JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49416790/