QCheckBox 互斥勾选框

#include "mainwindow.h"
#include "ui_mainwindow.h"



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QList< QCheckBox *> checkBoxList = this->findChildren<QCheckBox *>();
    mutexCheckBox(checkBoxList,false);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// QCheckBox 互斥勾选框,unchecked 是否处理未选中时,其他可选框变成了选中
void mutexCheckBox(QList< QCheckBox *> checkBoxList,bool unchecked)
{
    for(auto check:checkBoxList)
    {
        if(check)
        {
            QCheckBox::connect(check,&QCheckBox::clicked,[=]{
                Qt::CheckState checkState = check->checkState();
                for(auto it:checkBoxList)
                {
                    if(it && it != check)
                    {
                        if(checkState == Qt::Unchecked)
                        {
                            if(unchecked)
                                it->setCheckState(Qt::Checked);
                        }
                        else
                            it->setCheckState(Qt::Unchecked);
                    }
                }
            });
        }
    }
}

只有一个可选框会被勾选

猜你喜欢

转载自blog.csdn.net/hss2799/article/details/113180008