How to use a for loop to iterate over dynamically named variables (var1, var2, ...)

Viewed 75

I am trying to make a GUI using PyQt5. I have a couple of buttons say 4 which call the same function. A click on a button calls the same function to plot the data associated with each button.

radiobutton1.clicked.connect(self.fun)
radiobutton2.clicked.connect(self.fun)
radiobutton3.clicked.connect(self.fun)
radiobutton4.clicked.connect(self.fun)

Since each line of code is the same except the name of the button, is there a way instead of writing almost the same code four times, I use a for loop to generate the code?

2 Answers

You should initialize them in a loop, then append all of the objects to a list. Then, in this case, all you'd have to do is iterate over the list and call the .clicked.connect() method on each object.

radio_buttons = list()

for i in range(1, 5):
    temp_radio_button = QRadioButton("Radio Button")
    radio_buttons.append(temp_radio_button)

....

for radio_button in radio_buttons:
    radio_button.clicked.connect(self.fun)

I know it does not apply to this case, but for those who use QtDesigner and need to access the widgets later, this can be an option:

def get_all_objects(self,label,window,widget_class):
    for widget in filter(lambda entry: match(label,entry.objectName()),window.findChildren(widget_class)):
        yield widget

for widget in self.get_all_objects('radiobutton',MainWindow,QtWidgets.QRadioButton):
    widget.clicked.connect(self.fun)

Note:MainWindow can be replaced by a page on a StackedWidget if all your target widgets are in the same page.

Related