Check all checkBoxes inside of a checkable groupBox by checking and unchecking the GroupBox

4k views Asked by At

I have a GroupBox and inside of it I have 6 checkBoxes. I want them to be checked when I check the GroupBox and unchecked when I uncheck the GroupBox, like toggling all of them.

Something like:

for box in self.GroupBox.findChildren(QtGui.QCheckBox):
    if self.GroupBox.isChecked()==True:
        box.setChecked ==True
    else:
        pixel_box.setChecked == False

How Can I do that?

1

There are 1 answers

4
eyllanesc On BEST ANSWER

These changes must be made every time the QGroupBox changes, so it provides the toggled signal, so a slot will be connected and the changes will be made.

According to the docs:

checkable : bool

This property holds whether the group box has a checkbox in its title

If this property is true, the group box displays its title using a checkbox in place of an ordinary label. If the checkbox is checked, the group box's children are enabled; otherwise, they are disabled and inaccessible.

From the above it is observed that the children are disabled, and this is an unexpected situation, but ours is to enable it.

From all of the above the following should be done:

    self.GroupBox.toggled.connect(self.onToggled)
    self.GroupBox.setCheckable(True)

def onToggled(self, on):
    for box in self.sender().findChildren(QtGui.QCheckBox):
        box.setChecked(on)
        box.setEnabled(True)

An example that implements the above is the following:

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setLayout(QtGui.QVBoxLayout())
        self.GroupBox = QtGui.QGroupBox(self)

        self.GroupBox.setLayout(QtGui.QVBoxLayout())
        for i in range(6):
            checkbox = QtGui.QCheckBox("{}".format(i), self.GroupBox)
            self.GroupBox.layout().addWidget(checkbox)

        self.layout().addWidget(self.GroupBox)
        self.GroupBox.toggled.connect(self.onToggled)
        self.GroupBox.setCheckable(True)

    def onToggled(self, on):
        for box in self.sender().findChildren(QtGui.QCheckBox):
            box.setChecked(on)
            box.setEnabled(True)


if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())