I have a grid of buttons with each button residing inside it's own groupbox. I want to dynamically update these button's labels.
It's not clear to me how to address these buttons after being created in iteration and is there a way to just address their object names.
The documentation that I've read doesn't appear to include any methods for settext via object name. Is this possible or is there a better way to do this?
PyQt5, Python 3.6
If you have put a name to the widget with the function:
your_widget.setObjectName(your_name)
You can access it through the parent through the findChild
function:
your_parent_widget.findChild(name_class, your_name)
Example:
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_())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With