简体   繁体   English

为什么将我的QRadioButtons添加到单独的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()

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. 我一直在努力理解为什么在将两组QRadioButton添加到它们各自的QButtonGroup之后,它们仍然像在同一个父对象下一样运行。 I need the 'fruit' QRadioButtons to work independently of the 'junk' QRadioButtons. 我需要“水果” QRadioButton与“垃圾” QRadioButton独立工作。

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? 将QRadioButtons添加到QVBoxLayout之后,我是否以某种方式重写QButtonGroup?

I only have PyQt5 available for testing, but was able to reproduce your problem with it. 我只有PyQt5可用于测试,但是能够重现您的问题。

When defining the layout in create_layout , buttonGroup1 and buttonGroup2 are deleted on return. create_layout定义布局时,将在返回时删除buttonGroup1buttonGroup2 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 : 例如,可以通过在create_layout的末尾添加以下内容来完成此操作:

def create_layout(self):

    ...

    self.buttonGroups = buttonGroup1, buttonGroup2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM