Search code examples
pythonpyqtpyqt5qcheckbox

Count number of QCheckBox checked in a layout - PyQt5


I need to count the number of QCheckbox checked in a layout (called "grid_checkbox"). My code has two steps. The first step consists to add QCheckbox and the second step consists to count those which are checked.

def add_checkbox(self):
    for i in range(0, 5):
        for j in range(1):
            self.check_boxes = QtWidgets.QCheckBox("checkbox_%i" % i)
            self.grid_checkbox.addWidget(self.check_boxes,i,j)
            self.check_boxes.stateChanged.connect(self.count_checkbox)

def count_checkbox(self):
    nb_ischecked = 0
    for i in range(0, self.grid_checkbox.count()):
        self.current_checkbox = getattr(self, "checkbox_%i" % i)
        if self.current_checkbox.isChecked(): nb_ischecked = nb_ischecked + 1
    print(nb_ischecked)

Error:

AttributeError: 'MyApp' object has no attribute 'checkbox_0'

Solution

  • You are on the right track, you are just not accessing the widgets quite right.

    Try:

    def count_checkbox(self):
        nb_ischecked = 0
        for x in range(self.grid_checkbox.count()):
            if self.grid_checkbox.itemAt(x).widget().isChecked():
                nb_ischecked += 1
        print(nb_ischecked)