2

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_())
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Maxwe11
  • 97
  • 1
  • 1
  • 9

1 Answers1

3

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.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • It works but I have the webengineview in a centeral widget of a Qmainwindow so how I would make this work. I tried to return self.widget instead of self but didnt work. – Maxwe11 Dec 19 '17 at 22:24
  • 1
    @Maxwe11. You shouldn't change anything - it must be `return self`. There has to be a separate subclass of `QWebEngineView`, exactly as shown in my answer. Create an instance of `HtmlView` and set it as the central widget of the `QMainWindow`. – ekhumoro Dec 19 '17 at 22:47
  • Done it but there is one more problem, When it createswindow the back history is not accessible anymore. is there any other way to do it? how i can just mimic the follow link in context menu of qwebengine? – Maxwe11 Dec 20 '17 at 00:26