-2

There are 20 checkboxes in the user's window, in the code their name is checkbox_1, checkbox_2, ... checkbox_20. To activate all the checkboxes at the same time, I use this algorithm:

def select_all_W(self):
    self.Ui.checkBox_1.setChecked(True)
    self.Ui.checkBox_2.setChecked(True)
    # .................................
    self.Ui.checkBox_20.setChecked(True)

This makes the code very large and heavy. Is it possible to do the same thing through some function or, for example, through a loop:

for i in range 20
    self.Ui.checkBox_[i].setChecked(True)

In other words, how can you simplify the activation of a large number of window elements? At the bottom is a part of the program code where the enumeration of checkbox values is implemented.

class Win_menu(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.Ui = Ui_MainWindow()
        self.Ui.setupUi(self)
        self.show()
      
        self.Ui.pushButton_3.clicked.connect(self.select_all_W)
        self.Ui.pushButton_4.clicked.connect(self.select_all_W)
        self.Ui.pushButton_5.clicked.connect(self.select_all_A)
        self.Ui.pushButton_6.clicked.connect(self.select_all_A)
    
    def win_dlg(self):

        self.setup_games()
        self.Win_menu4 = Win_menu4()
        self.Win_menu4.show()

def setup_games(self):

        global warriors, magics, scouts, healers, special_W, special_M, special_S, special_H, leutents, cardOL, base_cardOl

        if self.Ui.checkBox_1.isChecked():
            warriors.extend(hero_B_W)
            magics.extend(hero_B_M)

        ....
        if self.Ui.checkBox_9.isChecked():
            warriors.append('Karnon')
        if self.Ui.checkBox_10.isChecked():
            warriors.append('korbin')
        if self.Ui.checkBox_11.isChecked():
            warriors.append('Kruzbek')

def select_all_A(self):
        self.Ui.checkBox_49.setChecked(True)
        self.Ui.checkBox_50.setChecked(True)
        self.Ui.checkBox_51.setChecked(True)


def reset_all_A(self):

        self.Ui.checkBox_49.setChecked(False)
        self.Ui.checkBox_50.setChecked(False)
        self.Ui.checkBox_51.setChecked(False)

hero_B_W = ['Grisban', 'Sindrael']
hero_B_M = ['Tarcha', 'Leorik']

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Win_menu()
    window.show()

    sys.exit(app.exec_())
16
  • This question is similar to: How can I select a variable by (string) name?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Mar 28 at 6:54
  • Alternatively - How do I create variable variables? Commented Mar 28 at 7:00
  • I don't need to create checkbox widgets in the window, they already exist and each has its own variable. The only problem is to activate or deactivate the checkboxes through a minimum number of lines of code. The suggested options did not work. Commented Mar 28 at 9:28
  • 2
    @Sergey In Python, coded named references (the "written" name associated to an object, like x or self.something) are not dynamic and there's no semantic syntax to allow that directly in the name. Not only self.Ui.checkBox_[i] wouldn't allow you to access objects with names starting with "checkBox_", but it also has a very different meaning, as square brackets are used for item access: the attempt above would be valid only if checkBox_ was an item based object (like a list). If the objects are referenced as attributes, use getattr(): getattr(self.Ui, f'checkBox_{i}'). Commented Mar 28 at 15:59
  • @Sergey If you want something like this to work, you need to refactor your code. These widgets need to be elements of a list, not individual variables. See that second link for more detail. Commented Mar 28 at 16:29

1 Answer 1

1

The problem is that you declared the checkboxes independently of one another. If you put them into an array or list, then you can do that. Here's an example:

for i in range(20):  # Create 20 checkboxes
            checkbox = QCheckBox(f"Checkbox {i+1}")
            self.checkboxes.append(checkbox)
            self.layout.addWidget(checkbox)

    def check_all(self):
        for checkbox in self.checkboxes:
            checkbox.setChecked(True)

# here's an example of how to create your own array of button objects
def select_all_W(self):
    checkboxes = [
        self.Ui.checkBox_1,
        self.Ui.checkBox_2,
        # add more checkboxes here as needed then you can use it in the code above
    ]

Something like this. Obviously you'll have to change it to suit your needs.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the advice, but the checkbox widgets have already been created in Qtdesigner in the dialog box, and "self.layout.addWidget(checkbox)" as far as I understand creates these widgets in the window. But I need to process all the widgets already available in the created dialog box by clicking a button. Do I understand correctly that this line allows you to replace the variable "checkbox_" during the execution of the function. ``` self.Ui.checkBox.setChecked(True)``` to the function ``` self.Ui.checkBox_i.setChecked(True) ````
I don't need to create checkbox widgets in the window, they already exist and each has its own variable. The only problem is to activate or deactivate the checkboxes through a minimum number of lines of code. The suggested options did not work.
@Moseph The OP is using a pyuic generated file (as shown in their previous posts), meaning that your suggestion is not valid unless the generated code is manually modified, which is almost always discouraged (starting from the header comment contained in those files) and generally considered bad practice unless the editor really knows what they're doing, how those files are created and used: if they do, they don't need to do any of that, if they don't, they shouldn't do it to begin with.
@Sergey Can you create an array of objects on your own? Like: def select_all_W(self): checkboxes = [ self.Ui.checkBox_1, self.Ui.checkBox_2, # add more checkboxes here as needed ] This way you're not changing the structure of the variable from the framework but instead creating your own array of button objects. I added it in my answer above
@Moseph thanks for the advice) I have 75 checkbox items and each is linked to a specific variable or list. If the user selects one or more checkboxes, the program adds items corresponding to these checkboxes to the general database. So it turns out that it is possible to create an array, but how is it possible to save variables to them? Now I will try to correct the question and the code in it so that the idea is clear.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.