Search code examples
pythonpyqtqcheckboxqgroupbox

How to get the state of Qcheckbox that is present inside the QGroupbox in PyQt


My project contains Qdialog having multiple QGroupbox.Each GroupBox contains some number of checkboxes.The list of checkboxes is same for all the groupbox. I dont have much reputation to load an image :(

Here the user is able to select the checkboxes based on his need and presses the ok button.Once the Ok Button is pressed, I should be able to get the list of checkboxes checked by the user.

I am creating the checkboxes in a loop, here is the code:

def createGroupBox(self,livename,shotlist):        

    groupBox = QtGui.QGroupBox("Live-"+livename)        
    grpLayout = QtGui.QVBoxLayout()
    i=0
    while  i != (len(shotlist)-2):
        qChkBx_shot = QtGui.QCheckBox("Shot-"+shotlist[i], self)
        qChkBx_shot.stateChanged.connect(lambda: self.groupcheckBoxToggled(livename,qChkBx_shot.text()))
        grpLayout.addWidget(qChkBx_shot,QtCore.Qt.AlignCenter)
        i +=1

    groupBox.setLayout(grpLayout)
    return groupBox

GroupBox with the below code:

def InitUi(self,livelist,shotlist):
    scrolllayout = QtGui.QGridLayout()

    scrollwidget = QtGui.QWidget()
    scrollwidget.setLayout(scrolllayout)

    scroll = QtGui.QScrollArea()
    scroll.setWidgetResizable(True)  # Set to make the inner widget resize with scroll area
    scroll.setWidget(scrollwidget)

    i=0
    length = len(livelist)-2
    x,y=0,0 

    while x <=  math.ceil(length/4):
        for y in range(0,4):
            if (i < (length)):
                groupbox=self.createGroupBox(livelist[i],shotlist)
                self.groupboxes.append(groupbox)
                scrolllayout.addWidget(groupbox, x, y)
            y +=1
            i +=1
        x+=1

    self.Okbutton = QtGui.QPushButton('OK',self)
    self.Okbutton.clicked.connect(lambda: self.buttonPressed())
    self.Okbutton.setMaximumWidth(100)
    layout = QtGui.QVBoxLayout()
    layout.addWidget(scroll)

    layout.addWidget(self.Okbutton,QtCore.Qt.AlignRight)
    self.setLayout(layout)        
    self.setWindowTitle("Customized LiveShotLiveSwitching")
    self.resize(1200, 500) 
    self.show()

Here my query is, I could able to retrive the value as which groupbox is been activated and I couldn't able to get the list of checkboxes checked under that groupbox.

Can anybody help me to solve this...


Solution

  • Make the groupbox the parent of each checkbox:

        qChkBx_shot = QtGui.QCheckBox("Shot-"+shotlist[i], groupBox)
    

    Now you can iterate over the checkboxes of a groupbox with:

        for checkbox in groupbox.findChildren(QtGui.QCheckBox):
            print('%s: %s' % (checkbox.text(), checkbox.isChecked()))
    

    And to get the groupbox the checkbox belongs to:

        groupbox = checkbox.parent()