如何用qwebengine制作分页浏览器

how to make tabbed browser with qwebengine

我有一些 pyqt5 代码,我正在尝试制作选项卡式浏览器,以及当我单击目标 _blank link 时它如何在新选项卡中打开 link。另外,由于我还是 PyQt5 的新手并且正在练习这个项目,所以我需要一些 help.In 我有 3 类 的代码,一个是主窗口,一个是 webview,一个是网页。这是代码:

class Ui_MainWindow(QMainWindow):

    def __init__(self):
         super(Ui_MainWindow, self).__init__()
         self.setupUi(self)

    def setupUi(self, MainWindow):
         self.centralwidget = QtWidgets.QWidget(MainWindow)
         self.centralwidget.setObjectName("centralwidget")
         self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
         self.tabWidget.setGeometry(QtCore.QRect(0, 75, width, height))
         self.tabWidget.setObjectName("tabWidget")
         self.loadUrl("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_a_target")
    def loadUrl(self, url):
        self.b = HtmlView()
        self.tabWidget.setCurrentIndex(self.tabWidget.addTab(self.b, 'loading...'))
        self.b.load(QUrl(url))
class WebEnginePage(QWebEnginePage):
    def __init__(self, parent=None):
         super(WebEnginePage, self).__init__(parent)
    def acceptNavigationRequest(self, url,  _type, isMainFrame):
        if (_type == QWebEnginePage.NavigationTypeLinkClicked):
             Ui_MainWindow.loadUrl(Ui_MainWindow, url)
             return True
        return QWebEnginePage.acceptNavigationRequest(self, url,  _type, isMainFrame)
class HtmlView(QWebEngineView):
    def __init__(self, parent=None):
        super(HtmlView, self).__init__()
        self.setPage(WebEnginePage(self))

classes 是抽象,也就是说,它们是无用的,但我创建了一个 class 的对象,而您在指令 Ui_MainWindow.loadUrl(Ui_MainWindow, url) 中使用的是 class 在不创建对象的情况下,您必须做的是通过实例使用相同的对象,如下所示:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

class TabWidget(QTabWidget):
    def __init__(self, *args, **kwargs):
        QTabWidget.__init__(self, *args, **kwargs)
        url = QUrl("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_a_target")
        view = HtmlView(self)
        view.load(url)
        ix = self.addTab(view, "loading ...")

class HtmlView(QWebEngineView):
    def __init__(self, *args, **kwargs):
        QWebEngineView.__init__(self, *args, **kwargs)
        self.tab = self.parent()

    def createWindow(self, windowType):
        if windowType == QWebEnginePage.WebBrowserTab:
            webView = HtmlView(self.tab)
            ix = self.tab.addTab(webView, "loading ...")
            self.tab.setCurrentIndex(ix)
            return webView
        return QWebEngineView.createWindow(self, windowType)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    main = TabWidget()
    main.show()
    sys.exit(app.exec_())