pyqt动态生成QMenu操作并连接 [英] pyqt dynamic generate QMenu action and connect
问题描述
仍在学习pyqt的工作方式.我想动态生成一个customContextMenu并与一个函数连接.到目前为止,我得到了以下内容,但连接部分无法正常工作?
Still learning how pyqt works. I want to dynamically generate a customContextMenu and connect with a function. So far I got the following but the connect part not working ?
import sys
from PyQt4 import QtGui, QtCore
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
# create button
self.button = QtGui.QPushButton("test button", self)
self.button.resize(100, 30)
# set button context menu policy
self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.connect(self.button, QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), self.on_context_menu)
self.popMenu = QtGui.QMenu(self)
def on_context_menu(self, point):
self.popMenu.clear()
#some test list for test
testItems = ['itemA', 'itemB', 'itemC']
for item in testItems:
action = self.btn_selectPyFilterPopMenu.addAction("Selected %s" % item)
self.connect(action,QtCore.SIGNAL("triggered()"),self,QtCore.SLOT("printItem('%s')" % item))
self.popMenu.exec_(self.button.mapToGlobal(point))
@pyqtSlot(str)
def printItem(self, item):
print item
def main():
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()
推荐答案
您的代码几乎正确.您只需要使用默认参数将信号连接到lambda
,如下所示:
Your code is almost right. You just need to connect the signals to a lambda
with a default argument, like this:
for item in testItems:
action = self.popMenu.addAction('Selected %s' % item)
action.triggered.connect(
lambda chk, item=item: self.printItem(item))
默认参数可确保每个lambda
获取 current 循环变量的副本.还要注意,还需要一个初始的chk
参数.这是因为triggered
信号默认发送其当前检查状态(是或否),这会破坏lambda
的item
参数.
The default argument ensures that each lambda
gets a copy of the current loop variable. Also note that an initial chk
argument is also required. This is because the triggered
signal sends its current checked-state (true or false) by default, which would clobber the item
argument of the lambda
.
最后,我强烈建议您在新式语法时使用连接信号-旧样式可能很容易出错,而Python则要少得多.
Finally, I would urge to use the new-style syntax when connecting signals - the old style can be very error-prone, and is far less pythonic.
这篇关于pyqt动态生成QMenu操作并连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!