Python PyQt5窗口无法打开新窗口或外部URL链接上的选项卡单击

时间:2019-04-02 10:22:28

标签: python python-3.x pyqt5

我需要使用pyQt5打开一个URL。该页面具有几个打开新窗口的链接。 pyQt5为URL打开了一个窗口,但是在单击应该打开一个新窗口的链接后,没有执行任何操作。 PS我正在使用pyQt5.6

我已经在Linux centOs上尝试过,但是没有用。

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://gmail.com"));
    w.show()
    sys.exit(app.exec_())

我希望它在任何网页上单击target ='_ blank'都会打开一个新窗口。

1 个答案:

答案 0 :(得分:2)

您必须重写createWindow方法并返回QWebEngineView,但是为了不使对象不被分散,该对象必须是另一个窗口的子对象,或者是具有较长生命周期的容器的一部分。

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