更新时间:2022-03-06 21:51:02
你必须重写 createWindow 方法并返回一个 QWebEngineView,但是要使对象不被干扰,它必须是另一个窗口的子窗口或者是某个窗口的一部分具有更长生命周期的容器.
You have to override the createWindow method and return a QWebEngineView, but for the object not to be distruded it must be the child of another window or be part of a container that has a longer life cycle.
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
class WebEnginePage(QtWebEngineWidgets.QWebEnginePage):
def acceptNavigationRequest(self, url, _type, isMainFrame):
if _type == QtWebEngineWidgets.QWebEnginePage.NavigationTypeLinkClicked:
return True
return super(WebEnginePage, self).acceptNavigationRequest(url, _type, isMainFrame)
class HtmlView(QtWebEngineWidgets.QWebEngineView):
def __init__(self, windows, *args, **kwargs):
super(HtmlView, self).__init__(*args, **kwargs)
self.setPage(WebEnginePage(self))
self._windows = windows
self._windows.append(self)
def createWindow(self, _type):
if QtWebEngineWidgets.QWebEnginePage.WebBrowserTab:
v = HtmlView(self._windows)
v.resize(640, 480)
v.show()
return v
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
windows = []
w = HtmlView(windows)
w.load(QtCore.QUrl("https://gmail.com"));
w.show()
sys.exit(app.exec_())