如何在 PyQtWebEngine 中打开带有 target="_blank" 的超链接?

How to open hyperlink with target="_blank" in PyQtWebEngine?

我已经使用 pyqt5 制作了一个网络浏览器并且 PyQtWebEngine.It 工作正常但是当我点击带有 target="_blank" 的 hyperlink 然后它不起作用但是我将如何修复它.您可以通过单击此 link https://github.com/SaptakBhoumik/WebPlus 查看其源代码 .请查看我的代码并告诉我该怎么做

the docs 所述:

_blank: usually a new tab, but users can configure browsers to open a new window instead.

即objective不是重新加载页面,而是创建一个新的标签页,然后获取该请求必须覆盖QWebEngineView(或QWebEnginePage)的createWindow方法:

from functools import cached_property
import sys


from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets


class WebView(QtWebEngineWidgets.QWebEngineView):
    def createWindow(self, type_):
        if not isinstance(self.window(), Browser):
            return

        if type_ == QtWebEngineWidgets.QWebEnginePage.WebBrowserTab:
            return self.window().tab_widget.create_tab()


class TabWidget(QtWidgets.QTabWidget):
    def create_tab(self):
        view = WebView()

        index = self.addTab(view, "(Untitled)")
        self.setTabIcon(index, view.icon())
        view.titleChanged.connect(
            lambda title, view=view: self.update_title(view, title)
        )
        view.iconChanged.connect(lambda icon, view=view: self.update_icon(view, icon))
        self.setCurrentWidget(view)
        return view

    def update_title(self, view, title):
        index = self.indexOf(view)
        self.setTabText(index, title)

    def update_icon(self, view, icon):
        index = self.indexOf(view)
        self.setTabIcon(index, icon)


class Browser(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setCentralWidget(self.tab_widget)

        view = self.tab_widget.create_tab()
        view.load(
            QtCore.QUrl(
                "https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_a_target"
            )
        )

    @cached_property
    def tab_widget(self):
        return TabWidget()


def main():
    app = QtWidgets.QApplication(sys.argv)
    w = Browser()
    w.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

注意:我建议您查看官方示例:WebEngine Widgets Simple Browser Example, in addition to its implementation in PySide2,它很容易转换为 PyQt5,其中实现了此功能和更多功能。