凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

pyqt5 QWebEngineView自定义浏览器

2019-10-17 python 3980
import sys
from PyQt5.QtCore import QUrl, QSize, Qt,,QCoreApplication
from PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit, QDesktopWidget, QAction, QToolBar, QTabWidget, \
    QWidget, QHBoxLayout, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtWebEngineWidgets import QWebEngineView,QWebEnginePage
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor

class WebEngineUrlRequestInterceptor(QWebEngineUrlRequestInterceptor):
     def __init__(self, parent=None):
        super().__init__(parent)
     def interceptRequest(self, info):
        url = info.requestUrl()
        # print(url.filename())
        # exit()
        if url.fileName() == "luckyMonster":
            # print(url.filename())
            print(str(info.requestUrl()))
            #print(info.requestUrl(), info.requestMethod(), info.resourceType(), info.firstPartyUrl())

        #print(info.requestUrl(),info.requestMethod(),info.resourceType(),info.firstPartyUrl())
        # luckyMonster

class WebView(QWebEngineView):
    def __init__(self, mainWin, parent=None):
        super().__init__(mainWin)
        self.mainWin = mainWin

    # 重写createwindow()
    def createWindow(self, QWebEnginePage_WebWindowType):
        new_webview = WebView(self.mainWin)
        self.mainWin.create_tab(new_webview)
        return new_webview


class Browser(QMainWindow):
    def __init__(self, mainWin, webview=None):
        super().__init__(mainWin)
        self.showFullScreen()
        self.mainWin = mainWin
        self.webview = webview
        self.initUI()

    def initUI(self):

        # self.setWindowFlags(Qt.FramelessWindowHint)  # 去掉标题栏的代码
        # 设置窗口标题
        self.setWindowTitle('LingBrowser')
        # 设置窗口图标
        self.setWindowIcon(QIcon('icons/penguin.png'))

        if self.webview == None:
            # 初始化一个 tab
            self.webview = WebView(self)  # self必须要有,是将主窗口作为参数,传给浏览器
            self.page = QWebEnginePage()
            # self.webview.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)  # 支持视频播放
            self.page.windowCloseRequested.connect(self.on_windowCloseRequested)  # 页面关闭请求
            self.page.profile().downloadRequested.connect(self.on_downloadRequested)  # 页面下载请求
           # self.webview.setUrl(QUrl("https://www.baidu.com"))

            #------------监听 加载内容url
            self.page.setUrl(QUrl(
                "https://music.163.com/"))

            self.t = WebEngineUrlRequestInterceptor()
            self.page.profile().setUrlRequestInterceptor(self.t)
            self.webview.setPage(self.page)
           # self.webview.load(QUrl("https://www.baidu.com"))

            # self.webview.setHtml("hello lingbrowser")
            #url = QUrl(QFileInfo("./blank.html").absolutePath()+"/blank.html")
            #self.webview.load(url)


        self.initToolbar(self.webview)
        self.setCentralWidget(self.webview)

        self.center()

    def on_downloadRequested(self):
        print("download..")

    def on_windowCloseRequested(self):
        print("close tab")

    def initToolbar(self, webview):
        ###使用QToolBar创建导航栏,并使用QAction创建按钮
        # 添加导航栏
        navigation_bar = QToolBar('Navigation')
        # 设定图标的大小
        navigation_bar.setIconSize(QSize(16, 16))
        # 添加导航栏到窗口中
        self.addToolBar(navigation_bar)

        # QAction类提供了抽象的用户界面action,这些action可以被放置在窗口部件中
        # 添加前进、后退、停止加载和刷新的按钮
        self.back_button = QAction(QIcon('icons/back.png'), 'Back', self)
        self.next_button = QAction(QIcon('icons/next.png'), 'Forward', self)
        self.stop_button = QAction(QIcon('icons/cross.png'), 'stop', self)
        self.reload_button = QAction(QIcon('icons/renew.png'), 'reload', self)

        self.back_button.triggered.connect(webview.back)
        self.next_button.triggered.connect(webview.forward)
        self.stop_button.triggered.connect(webview.stop)
        self.reload_button.triggered.connect(webview.reload)
        self.add_button = QAction(QIcon('icons/add_page.png'), 'add', self)

        # 将按钮添加到导航栏上
        navigation_bar.addAction(self.back_button)
        navigation_bar.addAction(self.next_button)
        navigation_bar.addAction(self.stop_button)
        navigation_bar.addAction(self.reload_button)
        navigation_bar.addAction(self.add_button)

        # 添加URL地址栏
        self.urlbar = QLineEdit()
        # 让地址栏能响应回车按键信号
        self.urlbar.returnPressed.connect(self.navigate_to_url)

        navigation_bar.addSeparator()
        navigation_bar.addWidget(self.urlbar)

        # 让浏览器相应url地址的变化
        webview.urlChanged.connect(self.renew_urlbar)

        webview.loadProgress.connect(self.processLoad)
        webview.loadFinished.connect(self.loadFinish)

        self.webBind()
        webview.show()

    def on_network_call(self, info):
        print(info)

    def loadPage(self, page):
        print(page)

    def processLoad(self, rate):
        # print(rate)
        pass

    def loadFinish(self, isEnd):
        if isEnd:
            print("load finished")

            # print(self.webview.page().profile())

    def webBind(self):
        # self.back_button.disconnect()
        # self.next_button.disconnect()
        # self.stop_button.disconnect()
        # self.reload_button.disconnect()
        # self.add_button.disconnect()

        self.back_button.triggered.connect(self.webview.back)
        self.next_button.triggered.connect(self.webview.forward)
        self.stop_button.triggered.connect(self.webview.stop)
        self.reload_button.triggered.connect(self.webview.reload)
        self.add_button.triggered.connect(self.mainWin.newTab)
        self.webview.urlChanged.connect(self.renew_urlbar)

    def navigate_to_url(self):
        q = QUrl(self.urlbar.text())
        if q.scheme() == '':
            q.setScheme('http')
        self.webview.setUrl(q)

    def renew_urlbar(self, q):
        # 将当前网页的链接更新到地址栏
        self.urlbar.setText(q.toString())
        self.urlbar.setCursorPosition(0)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    # 创建tab
    def create_tab(self, webview):
        self.tab = QWidget()
        self.mainWin.tabWidget.addTab(self.tab, "新标签页")
        self.mainWin.tabWidget.setCurrentWidget(self.tab)
        #####
        self.Layout = QHBoxLayout(self.tab)
        self.Layout.setContentsMargins(0, 0, 0, 0)
        self.Layout.addWidget(Browser(self.mainWin, webview=webview))


class LingBrowser(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initTab()
        # 初始化一个 tab
        self.newTab()

    def initTab(self):
        # self.setWindowFlags(Qt.FramelessWindowHint)  # 去掉标题栏的代码
        # 设置窗口标题
        self.setWindowTitle('LingBrowser')
        # 设置窗口图标
        self.setWindowIcon(QIcon('icons/penguin.png'))

        self.tabWidget = QTabWidget()
        self.tabWidget.setTabShape(QTabWidget.Triangular)
        self.tabWidget.setDocumentMode(True)
        self.tabWidget.setMovable(True)
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.tabCloseRequested.connect(self.close_Tab)
        self.tabWidget.currentChanged.connect(self.changeTab)

        self.setCentralWidget(self.tabWidget)
        # self.setGeometry(0, 0, 1400, 600)
        # self.showMaximized()
        self.setGeometry(300, 300, 1400, 600)
        self.center()

    def newTab(self):
        print("new tab")
        test = QPushButton("test")
        self.tab = QWidget()
        self.tabWidget.addTab(self.tab, "新标签页")
        self.tabWidget.setCurrentWidget(self.tab)
        #####
        self.Layout = QHBoxLayout(self.tab)
        self.Layout.setContentsMargins(0, 0, 0, 0)
        self.Layout.addWidget(Browser(self))

    # 关闭tab
    def close_Tab(self, index):
        if self.tabWidget.count() > 1:
            self.tabWidget.removeTab(index)
        else:
            self.close()  # 当只有1个tab时,关闭主窗口

    def changeTab(self, index):
        print("index:%d" % (index))

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    # 创建应用
    app = QApplication(sys.argv)
    QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL)
    # 创建主窗口
    window = LingBrowser()
    # 显示窗口
    window.show()
    # 运行应用,并监听事件
    sys.exit(app.exec_())

附件:icons

1.png

文章评论

0条评论