gpt4 book ai didi

python - pyqt 动态生成 QMenu Action 并连接

转载 作者:太空狗 更新时间:2023-10-30 00:25:13 25 4
gpt4 key购买 nike

仍在学习 pyqt 的工作原理。我想动态生成一个 customContextMenu 并连接一个函数。到目前为止,我得到了以下信息,但连接部分不起作用?

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,如下所示:

    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 信号默认发送其当前检查状态(true 或 false),这会破坏 lambdaitem 参数.

最后,我强烈建议使用 new-style syntax连接信号时 - 旧样式非常容易出错,并且远没有 Python 风格。

关于python - pyqt 动态生成 QMenu Action 并连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com