1
我正在使用Qt 5.7 QWebEngineView。Qt 5.7 - QWebEngineView - 将HTML按钮单击事件连接到C++/Qt插槽
如何HTML按钮单击事件连接到C++/PyQt5侧Q_SLOT?
我找不到一个明确的例子。
我正在使用Qt 5.7 QWebEngineView。Qt 5.7 - QWebEngineView - 将HTML按钮单击事件连接到C++/Qt插槽
如何HTML按钮单击事件连接到C++/PyQt5侧Q_SLOT?
我找不到一个明确的例子。
我创建了一个桥QObject,我在实现这个类时遇到的错误是我忘了添加@QtCore.pyqtSlot
装饰器,这很重要。
class Bridge(QtCore.QObject):
@QtCore.pyqtSlot()
def some_slot():
print("Slot Invoked")
在这里,我创建了一个QWebEngineView
和QWebChannel
并设置QWebEnginePage
的Web信道为信道,并且反之亦然。
然后我创造了我的QObject桥在self.helper_bridge
第一我没有用self
,只是通过其自身的使用helper_bridge
,当然这让我的应用程序崩溃
class MainWidget(object):
def __init__(self):
...
self.webView = QtWebEngineWidgets.QWebEngineView(parent)
channel = QtWebChannel.QWebChannel(self.webView.page())
self.webView.page().setWebChannel(channel)
self.helper_bridge = Bridge()
channel.registerObject("helperBridge", self.helper_bridge)
url = QtCore.QUrl("file:///path/to/index.html")
self.webView().page().load(url)
...
最后,index.html
页,
请注意Qt提供的第二个脚本。
在这里,我创建了一个QWebChannel
实例给予我的传输:qt.webChannelTransport
,并在回调中我处理了点击事件绑定,你可以看到。
<html>
<head>
</head>
<body>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js'</script>
<script src='qrc:///qtwebchannel/qwebchannel.js'></script>
<h1>hello</h1>
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
<a href='#go'>GO</a>
<script>
$(document).ready(function(){
new QWebChannel(qt.webChannelTransport, function(channel){
$('h1').on('click', function({
channel.objects.helperBridge.some_slot()
});
});
});
</script>
</body>
参考文献: