我的代码期望是:点击‘二级菜单2’时,其连接的函数能得到‘二级菜单2’这个菜单名,另外,menu_sec内容是非已知的,只能通过参数调取。但是像我这么写只能输出‘二级菜单3’,因为i最后是‘二级菜单3’。希望有懂怎么做的能帮我,谢了!
from PyQt5 import QtCore, QtWidgets
from PyQt5.Qt import QCursor
import sys
menu_sec=['二级菜单1','二级菜单2','二级菜单3']
class MainUi(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.main_layout = QtWidgets.QGridLayout()
self.setLayout(self.main_layout)
self.main_list = QtWidgets.QListWidget()
self.main_list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.main_list.customContextMenuRequested.connect(self.list_menu)
self.main_layout.addWidget(self.main_list, 0, 0)
self.show()
def list_menu(self, point):
menu=QtWidgets.QMenu()
action = menu.addMenu('一级菜单')
for i in menu_sec:
second = action.addAction(i)
second.triggered.connect(lambda: self.obt(i))
menu.exec_(QCursor.pos())
def obt(self, i):
print(i)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
gui = MainUi()
# gui.show()
sys.exit(app.exec_())