如何使用qwebengine制作标签式浏览器

时间:2017-12-23 00:54:54

标签: python python-3.x pyqt5 qwebview

我有一些pyqt5代码,我正在尝试制作选项卡式浏览器以及当我点击目标_blank链接时,如何在新标签页中打开该链接。另外,由于我还是PyQt5的新手并且正在练习这个项目,所以我需要一些帮助。在代码中我有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))

1 个答案:

答案 0 :(得分:0)

这些类是抽象的,也就是说,它们没用,但我创建了一个类的对象,你在Ui_MainWindow.loadUrl(Ui_MainWindow, url)指令中使用的是一个没有创建对象的类,你必须做的就是使用相同的对象通过我在下面显示的实例:

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