Python QPushButton 列表点击事件处理 - 打印索引并添加数字
Python QPushButton 列表点击事件处理 - 打印索引并添加数字
本文将介绍如何在 Python 中使用 PyQt5 库创建 QPushButton 列表,并通过点击事件获取按钮索引,将索引值打印出来并添加到 self.formula 中。
假设你已经创建了一个 QPushButton 列表,例如:
# 数字按键
numButton = [QPushButton(self) for i in range(10)]
# 0
numButton[0].setText('0')
numButton[0].setGeometry(buttonInitX+buttonSize, buttonInitY-buttonSize, buttonSize, buttonSize)
numButton[0].clicked.connect(self.pushZero)
# 1~9
for i in range(1, 10):
numButton[i].setText(str(i))
numButton[i].setGeometry(buttonInitX+buttonSize*((i-1)%3), buttonInitY+buttonSize*((i-1)//3), buttonSize, buttonSize)
要实现一个槽,当点击按钮 numButton[i] 时,print(i),并将 self.formula 加入数字 i 内容,你可以将按钮的索引作为参数传递给槽函数,并在槽函数中进行相应的操作。以下是一个示例代码:
def pushButtonClicked(self, index):
print(index)
self.formula += str(index)
# 在按钮创建的循环中连接槽函数
for i in range(10):
numButton[i].clicked.connect(lambda index=i: self.pushButtonClicked(index))
在这个示例中,我们将按钮的索引作为参数传递给 pushButtonClicked 槽函数,并在该函数中打印索引值并将其添加到 self.formula 中。请根据您的具体需求进行适当的修改。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qodP 著作权归作者所有。请勿转载和采集!