Is it possible to change default behavior of a checkable QGroupBox?

267 Views Asked by At

The question is pretty straight forward: is it possible to change the default behavior of a checkable QGroupBox object? I designed a user interface with many QLineEdit objects inside a checkable QGroupBox, the desired behavior is: when QGroupBox is not checked all of its children are enable and when it is checked all of its children are disable.

As you can see at the oficial QGroupBox documentation, it says:

If the check box is checked, the group box's children are enabled; otherwise, the children are disabled and are inaccessible to the user.

1

There are 1 best solutions below

3
eyllanesc On BEST ANSWER

One trick is to modify the painting so that when it is checked the check is not shown and vice versa:

#include <QtWidgets>

class GroupBox: public QGroupBox{
public:
    using QGroupBox::QGroupBox;
protected:
    void paintEvent(QPaintEvent *){
        QStylePainter paint(this);
        QStyleOptionGroupBox option;
        initStyleOption(&option);
        if(isCheckable()){
            option.state &= ~(isChecked() ? QStyle::State_On : QStyle::State_Off);
            option.state |= (isChecked() ? QStyle::State_Off : QStyle::State_On);
        }
        paint.drawComplexControl(QStyle::CC_GroupBox, option);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    GroupBox groupBox;
    groupBox.setCheckable(true);
    QVBoxLayout *vbox = new QVBoxLayout;
    vbox->addWidget(new QLineEdit);
    vbox->addWidget(new QLineEdit);
    vbox->addWidget(new QLineEdit);
    vbox->addStretch(1);
    groupBox.setLayout(vbox);
    groupBox.show();

    return a.exec();
}