为什么我的 QRadioButtons 'exclusive' 添加到单独的 QButtonGroups 后没有?

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()

我一直在努力理解为什么在将两组 QRadioButton 添加到它们各自的 QButtonGroup 之后,它们仍然像在同一个父对象下一样工作。我需要 'fruit' QRadioButtons 独立于 'junk' QRadioButtons 工作。

根据文档,'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'。

我是否在将 QRadioButtons 添加到 QVBoxLayout 后以某种方式覆盖了 QButtonGroup?

我只有 PyQt5 可用于测试,但能够重现您的问题。

create_layout 中定义布局时,buttonGroup1buttonGroup2 在 return 中被删除。您需要存储这些变量,以便它们在方法 return 之后存在。例如,这可以通过将以下内容添加到 create_layout 的末尾来完成:

def create_layout(self):

    ...

    self.buttonGroups = buttonGroup1, buttonGroup2