QWebEngineView - 如何在系统浏览器中打开链接

QWebEngineView - how to open links in system browser

我在 PySide 中有以下代码片段,需要将其转换为在 PySide2 中工作。 目的是在单击时强制所有 link 在系统浏览器中打开(而不是小部件试图加载它们):

from PySide.QtWebKit import QWebView, QWebPage

class HtmlView(QWebView):

    def __init__(self, parent=None):
        super(HtmlView, self).__init__(parent)
        self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) # not working in PySide2
        self.linkClicked.connect(self.openWebsite) # not working in PySide2

这是我的翻译尝试:

from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEnginePage

class HtmlView(QWebEngineView):

    def __init__(self, parent=None):
        super(HtmlView, self).__init__(parent)
        self.page().setLinkDelegationPolicy(QWebEnginePage.DelegateAllLinks) # not working in PySide2
        self.linkClicked.connect(self.openWebsite) # not working in PySide2

但是,QWebEngineView.linkClicked does not exist and neither does QWebEngineView.setLinkDelegationPolicy 或 QWebEnginePage.DelegateAllLinks.

如果没有上述内容,在 PySide2 中实现此目的的最佳方法是什么?

编辑:我检查了触发的 QEvents,但是当单击 link 时似乎没有事件被触发,所以没有来自 PySide/Qt4.8 的 linkClicked 事件我不知道如何加入这个。

谢谢, 坦率

你必须使用 acceptNavigationRequest:

This function is called upon receiving a request to navigate to the specified url by means of the specified navigation type type. isMainFrame indicates whether the request corresponds to the main frame or a child frame. If the function returns true, the navigation request is accepted and url is loaded. The default implementation accepts all navigation requests.

在您的情况下,当类型为 QWebEnginePage::NavigationTypeLinkClicked.

时,您必须拒绝并打开 url
from PySide2.QtCore import QUrl
from PySide2.QtGui import QDesktopServices
from PySide2.QtWidgets import QApplication
from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEnginePage


class WebEnginePage(QWebEnginePage):
    def acceptNavigationRequest(self, url,  _type, isMainFrame):
        if _type == QWebEnginePage.NavigationTypeLinkClicked:
            QDesktopServices.openUrl(url);
            return False
        return True

class HtmlView(QWebEngineView):
    def __init__(self, *args, **kwargs):
        QWebEngineView.__init__(self, *args, **kwargs)
        self.setPage(WebEnginePage(self))

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    w = HtmlView()
    w.load(QUrl(""));
    w.show()
    sys.exit(app.exec_())