簡體   English   中英

如何檢測pyside2中的Qwebengine內部的按鈕單擊

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

我用pyside2編寫了一個應用程序,該應用程序在QWebEngine中打開了一個網頁。

該網頁有2個按鈕,我不了解如何在pyside2應用模塊中檢測到按鈕單擊,我需要對該按鈕單擊執行其他操作。

下面是我的代碼

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_()

以下是輸出:

在此處輸入圖片說明

現在,我只想在用戶單擊“開始”按鈕時關閉我的應用程序。

QWebEnginePage允許您執行js,因此您可以找到按鈕 (例如id),並將其鏈接到回調,但這僅允許您在js中執行,而您希望在python中執行,因此解決方案是使用QWebChannel導出QObject並調用將關閉回調窗口的函數。 加載頁面后必須完成對象的導出,因此必須使用loadFinished信號。

在我的示例中,我使用一個按鈕來指示窗口是否已正確加載,因此如果按鈕為紅色,則必須按下該按鈕。

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