简体   繁体   English

如何检测pyside2中的Qwebengine内部的按钮单击

[英]How to detect button click inside Qwebengine in pyside2

I wrote an app in pyside2, which opening a webpage in QWebEngine. 我用pyside2编写了一个应用程序,该应用程序在QWebEngine中打开了一个网页。

That web page has 2 buttons, I am not understanding how can I detect a button click in pyside2 app module, I need to perform other operation on that button click. 该网页有2个按钮,我不了解如何在pyside2应用模块中检测到按钮单击,我需要对该按钮单击执行其他操作。

Example

below is my code 下面是我的代码

from PySide2.QtWidgets import QApplication
from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from PySide2.QtCore import QUrl

class WebEnginePage(QWebEnginePage):
    def __init__(self, *args, **kwargs):
        QWebEnginePage.__init__(self, *args, **kwargs)
        self.featurePermissionRequested.connect(self.onFeaturePermissionRequested)

    def onFeaturePermissionRequested(self, url, feature):
        if feature in (QWebEnginePage.MediaAudioCapture, 
            QWebEnginePage.MediaVideoCapture, 
            QWebEnginePage.MediaAudioVideoCapture):
            self.setFeaturePermission(url, feature, QWebEnginePage.PermissionGrantedByUser)
        else:
            self.setFeaturePermission(url, feature, QWebEnginePage.PermissionDeniedByUser)

app = QApplication([])

view = QWebEngineView()
page = WebEnginePage()
page.profile().clearHttpCache()
view.setPage(page)
view.load(QUrl("https://test.webrtc.org/"))

view.show()
app.exec_()

below is the output: 以下是输出:

在此处输入图片说明

Now I just want to close my application when a user clicks "start" button. 现在,我只想在用户单击“开始”按钮时关闭我的应用程序。

QWebEnginePage allows you to execute js so you could find the button for example the id, and link it to a callback but this will only allow you to execute it in js, and you want to do it in python, so the solution is to use QWebChannel to export a QObject and call the function that will close the window in the callback. QWebEnginePage允许您执行js,因此您可以找到按钮 (例如id),并将其链接到回调,但这仅允许您在js中执行,而您希望在python中执行,因此解决方案是使用QWebChannel导出QObject并调用将关闭回调窗口的函数。 The export of the object must be done after loading the page so the loadFinished signal must be used. 加载页面后必须完成对象的导出,因此必须使用loadFinished信号。

In my example I use a button to indicate if the window has been loaded correctly, so you must press the button if the button is red. 在我的示例中,我使用一个按钮来指示窗口是否已正确加载,因此如果按钮为红色,则必须按下该按钮。

from PySide2 import QtCore, QtWidgets, QtWebEngineWidgets, QtWebChannel


class WebEnginePage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self, *args, **kwargs):
        super(WebEnginePage, self).__init__(*args, **kwargs)
        self.loadFinished.connect(self.onLoadFinished)

    @QtCore.Slot(bool)
    def onLoadFinished(self, ok):
        print("Finished loading: ", ok)
        if ok:
            self.load_qwebchannel()
            self.run_scripts_on_load()

    def load_qwebchannel(self):
        file = QtCore.QFile(":/qtwebchannel/qwebchannel.js")
        if file.open(QtCore.QIODevice.ReadOnly):
            content = file.readAll()
            file.close()
            self.runJavaScript(content.data().decode())
        if self.webChannel() is None:
            channel = QtWebChannel.QWebChannel(self)
            self.setWebChannel(channel)

    def add_objects(self, objects):
        if self.webChannel() is not None:
            initial_script = ""
            end_script = ""
            self.webChannel().registerObjects(objects)
            for name, obj in objects.items():
                initial_script += "var {helper};".format(helper=name)
                end_script += "{helper} = channel.objects.{helper};".format(helper=name)
            js = initial_script + \
                 "new QWebChannel(qt.webChannelTransport, function (channel) {" + \
                 end_script + \
                 "} );"
            self.runJavaScript(js)

    def run_scripts_on_load(self):
        pass


class WebRTCPageView(WebEnginePage):
    def __init__(self, *args, **kwargs):
        super(WebRTCPageView, self).__init__(*args, **kwargs)
        self.featurePermissionRequested.connect(self.onFeaturePermissionRequested)
        self.load(QtCore.QUrl("https://test.webrtc.org/"))

    @QtCore.Slot(QtCore.QUrl, QtWebEngineWidgets.QWebEnginePage.Feature)
    def onFeaturePermissionRequested(self, url, feature):
        if feature in (QtWebEngineWidgets.QWebEnginePage.MediaAudioCapture,
                       QtWebEngineWidgets.QWebEnginePage.MediaVideoCapture,
                       QtWebEngineWidgets.QWebEnginePage.MediaAudioVideoCapture):
            self.setFeaturePermission(url, feature, QtWebEngineWidgets.QWebEnginePage.PermissionGrantedByUser)
        else:
            self.setFeaturePermission(url, feature, QtWebEngineWidgets.WebEnginePage.PermissionDeniedByUser)

    def run_scripts_on_load(self):
        if self.url() == QtCore.QUrl("https://test.webrtc.org/"):
            self.add_objects({"jshelper": self})
            js = '''
                var button = document.getElementById("startButton");
                button.addEventListener("click", function(){ jshelper.on_clicked() });
            '''
            self.runJavaScript(js)

    @QtCore.Slot()
    def on_clicked(self):
        print("clicked on startButton")
        QtCore.QCoreApplication.quit()


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = QtWidgets.QWidget()
    lay = QtWidgets.QVBoxLayout(w)

    button = QtWidgets.QToolButton()
    button.setStyleSheet('''
        QToolButton{
            border: 1px; 
            border-color: black; 
            border-style: outset
        }
        QToolButton[success="true"]{
            background-color: red; 
        }
        QToolButton[success="false"]{
            background-color: green; 
        }
    ''')

    def refresh_button(ok):
        button.setProperty("success", ok)
        button.style().unpolish(button)
        button.style().polish(button)

    refresh_button(False)

    view = QtWebEngineWidgets.QWebEngineView()
    page = WebRTCPageView()
    page.profile().clearHttpCache()
    view.setPage(page)

    progressbar = QtWidgets.QProgressBar()
    page.loadProgress.connect(progressbar.setValue)
    page.loadFinished.connect(refresh_button)

    hlay = QtWidgets.QHBoxLayout()
    hlay.addWidget(progressbar)
    hlay.addWidget(button)

    lay.addWidget(view)
    lay.addLayout(hlay)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM