QT Basics: A Simple Demonstration of the QButtonGroup Button Group

QButtonGroup is a button group, which is a container for combining or grouping controls, but it can be pulled out directly from the designer and used

When using QButtonGroup, you need to introduce  #include <QButtonGroup>

1. First create a widget project with QT, and add three selection boxes in the UI

Add a line CONFIG += console to the .pro file to automatically open the console at runtime

 2. Write code in widget.cpp 

Two slot functions are created here, respectively binding the buttonClicked signal and buttonToggled signal in QButtonGroup

#include "widget.h"
#include "ui_widget.h"
#include <QButtonGroup>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QButtonGroup *group = new QButtonGroup(this);
    // 将UI中创建好的选择框全部加入按钮组
    group->addButton(ui->checkBox1);
    group->addButton(ui->checkBox2);
    group->addButton(ui->checkBox3);

    // 选择框加入按钮组以后会默认变成单选  ,在这里可以改成多选
    group->setExclusive(false);


    // 链接创建好的槽函数
    QObject::connect(group,SIGNAL(buttonClicked(QAbstractButton*)),this,SLOT(Click(QAbstractButton*)));
    QObject::connect(group,SIGNAL(buttonToggled(QAbstractButton*,bool)),this,SLOT(Toggl(QAbstractButton*,bool)));

}

void Widget::Click(QAbstractButton * but)
{
    // 打印按钮组中被点击的选择框
    qDebug() << "按钮组被点击:" << but << but->isChecked();
}

void Widget::Toggl(QAbstractButton * but, bool check)
{
    // 打印按钮组中被触发的选择框
    qDebug() << "按钮组被触发:" << but << check;
}

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

3. The demonstration effect when the selection box is multiple selection:

It can be seen that when any selection box is selected or unselected , the buttonClicked and buttonToggled signals of the button group can be triggered once

 

4. // group->setExclusive(false); Comment out this line, the demonstration effect when the selection box is a single selection:

       can be seen,

When a selection box is selected , the buttonClicked and buttonToggled signals of the button group can be triggered

When another selection box is selected, the buttonToggled signal of the first selection box is triggered again ;

When clicking the selected selection box, the buttonToggled signal can be triggered separately

 关于 QButtonGroup  的一些信号:
buttonClicked(QAbstractButton *button)
buttonClicked(int id)
buttonPressed(QAbstractButton *button)
buttonPressed(int id)
buttonReleased(QAbstractButton *button)
buttonReleased(int id)
buttonToggled(QAbstractButton *button, bool checked)
buttonToggled(int id, bool checked)
 

Guess you like

Origin blog.csdn.net/qq_39085747/article/details/129251000