2
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?

lulufinder
  • 25
  • 1
  • 4

1 Answers1

3

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
tynn
  • 38,113
  • 8
  • 108
  • 143
  • Excellent! That did the trick. I'm fairly new to all of this but I think i'm still a bit fuzzy as to when I should I be using 'self' when defining attributes in my class. I've seen other people's pyside examples where the variables they're using to store their buttons are preceded with 'self' but their layouts are not. – lulufinder May 24 '15 at 20:31