一.新建 action
二.设置contextMenuPolicy
三.导出ui文件为py文件
# from123.py 为导出 py文件 form.ui 为 qt creator创造的 ui 文件
pyuic5 -o x:\xxx\from123.py form.ui
from123.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'form.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Test(object):
def setupUi(self, Test):
Test.setObjectName("Test")
Test.resize(800, 600)
self.listWidget = QtWidgets.QListWidget(Test)
self.listWidget.setGeometry(QtCore.QRect(210, 60, 256, 192))
self.listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listWidget.setObjectName("listWidget")
self.actionsa = QtWidgets.QAction(Test)
self.actionsa.setObjectName("actionsa")
self.retranslateUi(Test)
QtCore.QMetaObject.connectSlotsByName(Test)
def retranslateUi(self, Test):
_translate = QtCore.QCoreApplication.translate
Test.setWindowTitle(_translate("Test", "Test"))
self.actionsa.setText(_translate("Test", "sa"))
四. 在python文件 中 添加函数
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtSql import *
from PyQt5.QtGui import QIcon, QCursor
from from123 import Ui_Test
import sys
class QmyMainWindow(QWidget):
def __init__(self,parent=None):
super().__init__(parent)
self.ui = Ui_Test()
self.ui.setupUi(self)
def on_listWidget_customContextMenuRequested(self,pos): ##右键快捷菜单 策略情况
menuList=QMenu(self) #创建菜单
menuList.addAction(self.ui.actionsa)
menuList.exec(QCursor.pos()) #显示菜单
if __name__ == "__main__":
app = QApplication(sys.argv)
myApp = QmyMainWindow()
myApp.show()
sys.exit(app.exec()) #应用程序运行