我有一个按钮网格,每个按钮都位于它自己的组合框中。我想动态更新这些按钮的标签。
我不清楚如何在迭代中创建后解决这些按钮,并且有一种方法可以解决它们的对象名称。
我读过的文档似乎没有包含通过对象名称设置文本的任何方法。这是可能的还是有更好的方法来做到这一点?
PyQt5,Python 3.6
如果您使用该函数为小部件命名:
your_widget.setObjectName(your_name)
您可以通过findChild
函数通过父级访问它:
your_parent_widget.findChild(name_class, your_name)
例:
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
class Widget(QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent=parent)
self.verticalLayout = QVBoxLayout(self)
# self.verticalLayout.setObjectName("verticalLayout")
for i in range(10):
pushButton = QPushButton(self)
pushButton.setObjectName("pushButton{}".format(i))
pushButton.setText(str(i))
self.verticalLayout.addWidget(pushButton)
timer = QTimer(self)
timer.setInterval(1000)
timer.timeout.connect(self.updateText)
timer.start()
def updateText(self):
for i in range(10):
child = self.findChild(QPushButton, "pushButton{}".format(i))
counter = int(child.text())
child.setText(str(counter+1))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())