使用QWebEngine在同一窗口中打开任何链接(甚至_blank) [英] Make any link (even _blank) open in same window using QWebEngine
问题描述
我有这段代码可以访问/跟随我在同一窗口中单击的任何链接,即使它通常会在新窗口中打开.这样就不必右键单击,然后从上下文菜单中选择跟随链接".由于某些原因,它无法按预期工作.
I have this code that is supposed to visit/follow any link that I click in the same window, even if it would normally open in a new window. This would be instead of having to right-click and then select "Follow link" from context menu. For some reason, it doesn't work as expected.
这是代码:
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
class WebEnginePage(QWebEnginePage):
def acceptNavigationRequest(self, url, _type, isMainFrame):
if _type == QWebEnginePage.NavigationTypeLinkClicked:
return True
return QWebEnginePage.acceptNavigationRequest(self, url, _type, isMainFrame)
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://yahoo.com"));
w.show()
sys.exit(app.exec_())
推荐答案
If you want links to always open in the same window, you can reimplement the createWindow method, so that it returns the same view:
class HtmlView(QWebEngineView):
def createWindow(self, wintype):
return self
wintype
参数提供有关正在请求哪种类型的窗口的信息.您可能想以不同的方式对待对话框窗口.
The wintype
argument provides information about which type of window is being requested. You may want to treat dialog windows differently.
请注意,您的示例中的WebEnginePage
子类不需要此功能.
Note that the WebEnginePage
subclass in your example is not needed for this to work.
这篇关于使用QWebEngine在同一窗口中打开任何链接(甚至_blank)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!