Catch links in QtWebView and open default browser

I open the page in QtWebView (in PyQt, if that matters), and I want to open all the links in the default browser of the system. That is, clicking on the link should not change the site in QtWebView, but it should open it using the default browser. I want the user to not be able to modify the site in QtWebView.

How can i do this?

Thanks Albert

+7
qt qt4 pyqt qtwebkit
source share
2 answers

It does:

import sys, webbrowser from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://www.az2000.de/projects/javascript-project/")) web.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) def linkClicked(url): webbrowser.open(str(url.toString())) web.connect(web, SIGNAL("linkClicked (const QUrl&)"), linkClicked) web.show() sys.exit(app.exec_()) 
+9
source share

Updated example for PyQt5 (the magic is to reimplement the acceptNavigationRequest method):

 from PyQt5 import QtWidgets, QtCore, QtGui, QtWebEngineWidgets class RestrictedQWebEnginePage(QtWebEngineWidgets.QWebEnginePage): """ Filters links so that users cannot just navigate to any page on the web, but just to those pages, that are listed in allowed_pages. This is achieved by re-implementing acceptNavigationRequest. The latter could also be adapted to accept, eg URLs within a domain.""" def __init__(self, parent=None): super().__init__(parent) self.allowed_pages = [] def acceptNavigationRequest(self, qurl, navtype, mainframe): # print("Navigation Request intercepted:", qurl) if qurl in self.allowed_pages: # open in QWebEngineView return True else: # delegate link to default browser QtGui.QDesktopServices.openUrl(qurl) return False class RestrictedWebViewWidget(QtWidgets.QWidget): """A QWebEngineView is required to display a QWebEnginePage.""" def __init__(self, parent=None, url=None, html_file=None): super().__init__(parent) self.view = QtWebEngineWidgets.QWebEngineView() self.page = RestrictedQWebEnginePage() if html_file: print("Loading File:", html_file) self.url = QtCore.QUrl.fromLocalFile(html_file) self.page.allowed_pages.append(self.url) self.page.load(self.url) elif url: print("Loading URL:", url) self.url = QtCore.QUrl(url) self.page.allowed_pages.append(self.url) self.page.load(self.url) # associate page with view self.view.setPage(self.page) # set layout self.vl = QtWidgets.QVBoxLayout() self.vl.addWidget(self.view) self.setLayout(self.vl) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) web = RestrictedWebViewWidget(url="YOUR URL") # or YOUR local HTML file web.show() sys.exit(app.exec_()) 
0
source share

All Articles