Make any link (even _blank) open in same window using QWebEngine

懵懂的女人 提交于 2019-12-07 23:36:55

问题


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.

Here is the code:

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

回答1:


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

The wintype argument provides information about which type of window is being requested. You may want to treat dialog windows differently.

Note that the WebEnginePage subclass in your example is not needed for this to work.



来源:https://stackoverflow.com/questions/47893838/make-any-link-even-blank-open-in-same-window-using-qwebengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!