PyQt QtWebChannel:从 JavaScript 调用 Python 函数 [英] PyQt QtWebChannel: calling Python function from JavaScript
问题描述
我正在尝试使用 Qt 类 QWebEngineView
和 QWebChannel
在 HTML 页面和 Python 脚本之间建立简单的连接.目标只是在单击标题 时执行
foo()
.
I am trying, using Qt classes QWebEngineView
, and QWebChannel
to make a simple connection between HTML page and Python script. The goal is simply to execute foo()
when the header <h2>
is clicked.
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
的一个属性,以使其成为 global 但它没有用.
The problem seems to be that the variable backend
is not visible outside of the QWebChannel
constructor. I tried to make backend
an attribute of widnow
to make it global but it did not work.
推荐答案
问题不在于可见性,而是与点击事件的连接,文件的上传是从上到下所以你试图连接标题时它尚不存在,解决方案是重写HTML:
The problem is not the visibility but the connection with the click event, the upload of the file is from top to bottom so you are trying to connect the header when it does not yet exist, the solution is to rewrite the 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>
这篇关于PyQt QtWebChannel:从 JavaScript 调用 Python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!