PyQt5中自定义QWebEngineView的右键菜单

 实现代码

@author: daimashiren
@time:    2021/01/20

# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import QWebEngineView,QWebEngineSettings
from PyQt5.QtWidgets import QMenu, QWidget, QAction,QMessageBox



class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('My Browser')
        self.setGeometry(300,200,1200,800)
        self.setWindowFlags(Qt.FramelessWindowHint)

        #####创建tabwidget
        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.setCentralWidget(self.tabWidget)

        #自定义浏览器右键菜单
        self.web_menu = WebMenu()

        ####第一个tab
        self.webview = QWebEngineView(self)   #将主窗口作为参数,传给浏览器
        
        """关键代码"""
        self.webview.setContextMenuPolicy(Qt.CustomContextMenu)     #将浏览器右键菜单设置为用户自定义菜单
        self.webview.customContextMenuRequested.connect(self.MyBrowser_Menu)#将菜单的信号链接到自定义菜单槽函数
        """关键代码"""


        self.webview.load(QUrl("https://cn.bing.com/"))
        self.create_tab(self.webview)


    #创建tab
    def create_tab(self,webview):
        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(webview)


    #关闭标签
    def close_Tab(self,index):
        if self.tabWidget.count()>1:
            self.tabWidget.removeTab(index)
        else:
            QCoreApplication.quit()
            


    #创建自定义浏览器右键菜单
    def MyBrowser_Menu(self,pos):
        action = self.web_menu.exec_(self.webview.mapToGlobal(pos))
        if action == self.web_menu.save_act:
            self.save_slot()
        elif action == self.web_menu.reload_act:
            self.reload_slot()


    def save_slot(self):
        QMessageBox.information(self,"测试","测试保存设置")

    def reload_slot(self):
        QMessageBox.information(self,"测试","测试刷新设置")





#自定义的一个菜单类
class WebMenu(QMenu):
    def __init__(self):
        super(WebMenu, self).__init__()
        # 定义一个浏览器右键菜单
        self.save_act = QAction("保存")
        self.reload_act = QAction("刷新")
        self.addAction(self.save_act)
        self.addAction(self.reload_act)



if __name__ == "__main__":
    app = QApplication(sys.argv)
    the_mainwindow = MainWindow()
    the_mainwindow.show()
    sys.exit(app.exec_())

效果演示

 

你可能感兴趣的:(PyQt5,Python,pyqt5,python)