我正在尝试构建我从这里遇到的这个例子: Right click contextMenu on QPushButton
当我动态创建按钮时,如何让它工作?我想不出一种动态创建方法的方法on_context_menu
。
这是我到目前为止的代码。
import sys
from PyQt4 import QtGui,QtCore
import sip
class LayoutTest(QtGui.QWidget):
def __init__(self):
super(LayoutTest, self).__init__()
self.setGeometry(300, 300, 400, 200)
VmasterLayout = QtGui.QVBoxLayout(self)
self.Hbox = QtGui.QHBoxLayout()
for i in range(1,4):
self.butVal = 'buttonMenu_%s' % i
self.button = QtGui.QPushButton(self.butVal)
self.button.clicked.connect(self.allCheckButton)
self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.connect(self.button, QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), self.on_context_menu)
# create context menu
self.popMenu = QtGui.QMenu(self)
action = QtGui.QActionGroup(self, exclusive=True)
listVer = ['image_v001','image_v003','image_v012','image_v120','image_v140', 'image_v013']
for i, vDir in enumerate(sorted(listVer)):
x = action.addAction(QtGui.QAction( vDir, self, checkable = True))
x.triggered.connect(self.foo(x.text()))
self.popMenu.addAction(x)
self.popMenu.addSeparator()
self.Hbox.addWidget(self.button)
VmasterLayout.addLayout(self.Hbox)
def on_context_menu(self, point):
# show context menu
self.popMenu.exec_(self.button.mapToGlobal(point))
def foo(self, name):
def poo():
print 'Image version is: %s' % name
return poo
def allCheckButton(self):
point = QtGui.QCursor.pos()
print point
def run():
app = QtGui.QApplication(sys.argv)
ex = LayoutTest()
ex.show()
sys.exit(app.exec_())
if __name__ == "__main__":
run()