Search code examples
c++qtqt4qgroupboxqbuttongroup

Add a QGroupBox to a QButtonGroup


I have a group of 3 QRadioButtons and 2 checkable QGroupBoxes that need to all be mutually exclusive. I like the convenience of adding my radio buttons to a QButtonGroup to automatically handle this, but I can't seem to figure out how to add the QGroupBox to the button group because it doesn't inherit from QAbstractButton and I can't find access to its checkbox.

For example,

QRadioButton* rb1 = new QRadioButton("Button1");
QRadioButton* rb2 = new QRadioButton("Button2");
QRadioButton* rb3 = new QRadioButton("Button3");
QGroupBox* gb1 = new QGroupBox;
gb1->setCheckable(true);
QGroupBox* gb2 = new QGroupBox;
gb2->setCheckable(true);
QRadioButton* rb1 = new QRadioButton("Button1");

QButtonGroup* grp = new QButtonGroup;
grp->addButton(rb1);
grp->addButton(rb2);
grp->addButton(rb3);
grp->addButton(gb1);   //these two fail
grp->addButton(gb2);

Is there a simple way to accomplish this? I know that I can connect to QGroupBox's clicked() signal, but I rather do this more cleanly than that.


Solution

  • You can only add QAbstractButton derived classes to a QButtonGroup instance. So in your case if you want to handle the a QGroupBox as one of the exclusive items, I think you need to implement it by yourself. Maybe you could connect all SIGNALs from the mentioned widget to the same SLOT, and in that SLOT you can update the checked/unchecked widgets with the help of the sender function:

    QObject* object = sender();
    
    if ( object == groupBox1 )
    {
        // ...
    }
    else if ( object == groupBox1 )
    {
        // ...
    

    But if you need to do this in many places then you shall implement some kind of helper class for this purpose.