Search code examples
pythonqtpyqtpysideqradiobutton

Why aren't my QRadioButtons 'exclusive' after being added to separate QButtonGroups?


from PySide import QtCore
from PySide import QtGui

class UI(QtGui.QDialog):

    def __init__(self):

        super(UI,self).__init__()
        self.setWindowTitle('Test UI 2000')
        self.create_layout()

    def create_layout(self):

        mainLayout = QtGui.QVBoxLayout()
        self.setLayout(mainLayout)

        fruitLabel = QtGui.QLabel('Fruit')
        junkLabel = QtGui.QLabel('Junk')

        buttonGroup1 = QtGui.QButtonGroup()
        radioButtonA = QtGui.QRadioButton('Apple')
        radioButtonB = QtGui.QRadioButton('Pear')
        buttonGroup1.addButton(radioButtonA)
        buttonGroup1.addButton(radioButtonB)

        buttonGroup2 = QtGui.QButtonGroup()
        radioButtonC = QtGui.QRadioButton('Hotdog')
        radioButtonD = QtGui.QRadioButton('Hamburger')
        buttonGroup2.addButton(radioButtonC)
        buttonGroup2.addButton(radioButtonD)

        mainLayout.addWidget(fruitLabel)
        mainLayout.addWidget(radioButtonA)
        mainLayout.addWidget(radioButtonB)
        mainLayout.addWidget(junkLabel)
        mainLayout.addWidget(radioButtonC)
        mainLayout.addWidget(radioButtonD)

if __name__ == '__main__':

    try:
        ui.close()
    except:
        pass

    ui = UI()
    ui.setAttribute(QtCore.Qt.WA_DeleteOnClose)
    ui.show()

I've been struggling to understand why, after adding two sets of QRadioButtons to their own respective QButtonGroup, they still function as if they're under the same parent. I need the 'fruit' QRadioButtons to work independently of the 'junk' QRadioButtons.

According to the docs, 'If auto-exclusive is enabled (which it is by default), radio buttons that belong to the same parent widget behave as if they were part of the same exclusive button group'.

Am I somehow overriding the QButtonGroup after adding my QRadioButtons to my QVBoxLayout?


Solution

  • I only have PyQt5 available for testing, but was able to reproduce your problem with it.

    When defining the layout in create_layout, buttonGroup1 and buttonGroup2 are deleted on return. You need to store these variables for them to exist after method return. For example this can be done by adding the following to the end of create_layout:

    def create_layout(self):
    
        ...
    
        self.buttonGroups = buttonGroup1, buttonGroup2