PyQt5 中意外的 QMenu/QAction 行为



我正在尝试使用几个动态生成的操作构建一个QMenu。下面的代码在QMenu中创建了一个包含两个QAction的简单窗口。QMenu 用于菜单栏和按钮。


from PyQt5.QtWidgets import QMainWindow, QPushButton, QHBoxLayout, QAction, QMenu, QApplication
class MainWin(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setupGui()
self.setupMenu()


def setupGui(self): 
""" make a QpushButton for the QAction """
self.btn = QPushButton("Press me!", self)
self.btn.move(50,50)
self.layout().addWidget(self.btn)


def setupMenu(self):
self.menu = QMenu(self) # making the Qmenu
self.menu.setTitle('Broken menu')

for actName in ['neverTrig', 'alwaysTrig']:
act = QAction(actName, self)
act.triggered.connect(lambda : print(actName))
self.menu.addAction(act)

self.btn.setMenu(self.menu) #binding the menu to the button
self.menuBar().addMenu(self.menu) #binding the menu to the menuBar



if __name__ == '__main__':
app=QApplication([])
win = MainWin()
win.show()
app.exec_()

方法setupMenu()用两个不同的QAction填充QMenu。但是,无论单击哪个,它始终是最后一个触发的。即使单击了 neverTrig,也会打印 alwaysTrig。

我尝试了不同的语法,不使用lambda函数,保留对lambda函数的引用,保留对QAction的另一个引用,更详细,不那么冗长,以及不同版本的PyQt。无论最后一个 QAction 是什么,始终是触发

的那个。我在Windows和PyQt 5.15.2上使用Python 3.8.8

您将行为分配给同一个变量,这就是为什么您的触发器始终连接到最后一个变量的原因。尝试:

act1 = QAction('neverTrig', self)
act1.triggered.connect(lambda : print('whatever'))
self.menu.addAction(act1)
act2 = QAction('alwaysTrig', self)
act2.triggered.connect(lambda : print('whatever 2'))
self.menu.addAction(act2)

最新更新