简体   繁体   中英

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'

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM