gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:18 26 4
gpt4 key购买 nike

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

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 不存在,QWebEngineView 也不存在.setLinkDelegationPolicy 或 QWebEnginePage .DelegateAllLinks。

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

编辑:我检查了触发的 QEvent,但单击链接时似乎没有事件被触发,因此没有 linkClicked来自 PySide/Qt4.8 的事件我不知道如何 Hook 。

谢谢,坦率

最佳答案

您必须使用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("https://stackoverflow.com/questions/47736408/pyside2-qwebview-how-to-open-links-in-system-browser"));
w.show()
sys.exit(app.exec_())

关于python - QWebEngineView - 如何在系统浏览器中打开链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47736408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com