我在qpushbuttons
循环中创建了一些for
。我想要做的是通过上下文菜单访问它们的值(for循环迭代的数字)。
我可以创建按钮,点击左键,我会打印出他们的值。但是当我右键单击打开上下文菜单时,触发的命令self.value.triggered.connect(partial(self.get_value, number))
仅返回最高值。
为了通过上下文菜单中的get_value
条目获取值,我需要更改什么?
import sys
from functools import partial
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QAction, QMenu
from PyQt5.QtCore import Qt
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.buttons = []
self.value = []
self.context_menu = []
pos_value = [30, 50]
for number in range(0,4):
button_text = "Button " + str(number)
self.buttons.append(QPushButton(button_text, self))
self.buttons[number].move(*pos_value)
self.buttons[number].clicked.connect(self.buttonClicked)
pos_value[0] += 120
self.buttons[number].setContextMenuPolicy(Qt.CustomContextMenu)
self.buttons[number].customContextMenuRequested.connect(partial(self.open_context_menu, number))
self.context_menu.append(QMenu(self))
self.value.append(QAction('Get value ' + str(number), self))
self.context_menu[-1].addAction(self.value[-1])
self.value[-1].triggered.connect(partial(self.get_value, number))
self.setGeometry(300, 300, 600, 150)
self.show()
def buttonClicked(self):
sender = self.sender()
print(sender.text() + ' was pressed')
def get_value(self, value):
print('Value ' + str(value))
def open_context_menu(self, i, point):
self.context_menu[-1].exec_(self.buttons[i].mapToGlobal(point))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Main()
sys.exit(app.exec_())
编辑:我在程序中发现错误,因为我已经覆盖了变量self.value和self.context_menu。现在这已经修复,但错误仍然存在。
任何想法如何解决这个问题?
答案 0 :(得分:1)
def open_context_menu(self, i, point):
self.context_menu[-1].exec_(self.buttons[i].mapToGlobal(point))
# ^
# Your bug here