单选按钮QRadioButton

使用场景:多选一,即在一组单选按钮中,一次只能选中一个按钮

比如性别:"男女"2选1

属性和方法:

文本

// 获取和设置显示的文本
QString text() const
void setText(const QString &text)

选中状态

// 获取和设置单选按钮的选中状态
bool isChecked() const
void setChecked(bool)
  • 可以通过鼠标点击来切换单选按钮的选中状态
  • 也可通过setChecked(bool) 来设置切换

自动排他

单选按钮就是为了多选一的,因此这个属性默认是使能

// 获取和设置自动排他
bool autoExclusive() const
void setAutoExclusive(bool)

多选一需要满足的条件:

同一组的单选按钮需要在同一个布局或者ButtonGroup中;不同组的单选按钮放在不同的布局中

autoExclusive属性需要为true(单选按钮默认为true)

常用信号

// 单选按钮 QRadioButton 被点击时,会发出该信号
void clicked();

// 当单选按钮的选中状态发生改变时,会发射该信号
// 所谓状态改变,是指选中变为非选中,和非选中变为选中
void toggled(bool checked)

举例:

多个单选按钮放在一个buttonGroup中 ,实现多选一互斥

    QRadioButton* btn1=new QRadioButton(this);
    btn1->setText("本科");
    btn1->move(100,100);
    QRadioButton* btn2=new QRadioButton(this);
    btn2->setText("硕士");
    btn2->move(200,100);
    QRadioButton* btn3=new QRadioButton(this);
    btn3->setText("博士");
    btn3->move(300,100);

    //将这三个单选按钮加到同一个ButtonGroup中实现多选一
    QButtonGroup* btn_group=new QButtonGroup(this);
    btn_group->addButton(btn1,0);//添加时可以设置对应的索引
    btn_group->addButton(btn2,1);
    btn_group->addButton(btn3,2);

    //可以使用btn_group的信号来获取选中的按钮
    connect(btn_group,&QButtonGroup::buttonClicked,this,[=](){
        //获取这个按钮组中选中的单选按钮
        auto checked_btn=btn_group->checkedButton();
        QMessageBox::information(this,"",checked_btn->text());
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值