0
我試圖建立過這個例子中,我已經跨越來自這裏: Right click contextMenu on QPushButton蟒蛇PyQt4中文本菜單上的多個按鈕
我將如何得到這個當我動態創建按鈕的工作?我無法弄清楚動態創建方法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()