Qt-如何将小部件放在互斥的组中?

2022-02-27 00:00:00 qt5 qt c++ qgroupbox

我希望执行以下操作:

示例

但使用单选按钮而不是复选框。在上面的图片中,小工具被放入可以启用/禁用的组中,但我希望一次只启用一个组(在本例中,A组和C组都被启用)。

我使用QGroupBox执行了上面的示例,但据我所知,它只提供普通的复选框,而不是单选按钮。


解决方案

QGroupBox中出现的复选框不是QCheckBox,它只是一幅图。因此,一种可能的解决方案是创建一个管理QGroupBox选中的类。

#include <QApplication>
#include <QGroupBox>
#include <QLineEdit>
#include <QRadioButton>
#include <QSlider>
#include <QVBoxLayout>

class ExclusiveManager: public QObject{
public:
    using QObject::QObject;
    void addGroupBox(QGroupBox *groupbox){
        if(groupbox){
            groupbox->blockSignals(true);
            groupbox->setChecked(m_groupboxs.isEmpty());
            groupbox->blockSignals(false);
            m_groupboxs << groupbox;
            connect(groupbox, &QGroupBox::toggled, this, &ExclusiveManager::onToggled);
        }
    }
private slots:
    void onToggled(bool on){
        QGroupBox *groupbox = qobject_cast<QGroupBox *>(sender());
        if(on){
            for(QGroupBox *g: m_groupboxs){
                if(g != groupbox && g->isChecked()){
                    g->blockSignals(true);
                    g->setChecked(false);
                    g->blockSignals(false);
                }
            }
        }
        else{
            groupbox->blockSignals(true);
            groupbox->setChecked(false);
            groupbox->blockSignals(false);
        }
    }
private:
    QList<QGroupBox *> m_groupboxs;
};

class Widget: public QWidget{
public:
    Widget(QWidget *parent=nullptr):QWidget(parent){
        setLayout(new QVBoxLayout);

        ExclusiveManager *manager = new ExclusiveManager(this);

        group_a = new QGroupBox("Group A");
        group_a->setCheckable(true);
        group_b = new QGroupBox("Group B");
        group_b->setCheckable(true);
        group_c = new QGroupBox("Group C");
        group_c->setCheckable(true);
        layout()->addWidget(group_a);
        layout()->addWidget(group_b);
        layout()->addWidget(group_c);

        manager->addGroupBox(group_a);
        manager->addGroupBox(group_b);
        manager->addGroupBox(group_c);

        QVBoxLayout *layA = new QVBoxLayout();
        layA->addWidget(new QLineEdit);
        group_a->setLayout(layA);

        QVBoxLayout *layB = new QVBoxLayout();
        layB->addWidget(new QRadioButton("Option 1"));
        layB->addWidget(new QRadioButton("Option 2"));
        group_b->setLayout(layB);

        QVBoxLayout *layC = new QVBoxLayout();
        layC->addWidget(new QSlider(Qt::Horizontal));
        group_c->setLayout(layC);
    }
private:
    QGroupBox *group_a;
    QGroupBox *group_b;
    QGroupBox *group_c;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

相关文章