Qt5.9中一组按钮QPushbutton形成互斥(有且只能选中一个)(单选按钮)

本文主要总结用一组按钮QPushbutton,实现有且只能选中一个按钮的功能,效果跟单选按钮一样。

要实单选按钮,只要用一个类QButtonGround就可以实现。

步骤1:调用函数QButtonGround::setExclusive(true)和QPushbutton::setCheckable(true);

步骤2:将相关的QPushbutton按钮添加进QButtonGround中,用函数QButtonGround::addButton();

步骤3:用布局管理器挂载按钮进行显示。

提醒:本文只是实现界面效果,要实现按钮触发功能,需要用到下面函数绑定QButtonGround的触发信号和槽函数;

connect(buttonGroup,SIGNAL(buttonClicked(int)),this,SLOT(buttonGroupSlot(int))),具体实现例子可以参考博主写的这篇博客:

https://blog.csdn.net/naibozhuan3744/article/details/82188037

 

1.1代码如下所示:

void Widget::initMenu()
{
    const QSize btnSize(120,90);

    QPushButton *btn1 = new QPushButton(tr("\n测试按钮"));
    btn1 ->setCheckable(true);
    btn1 ->setFixedSize(btnSize);
    btn1 ->setStyleSheet("QPushButton{background-image: url(:/1.png);background-repeat: no-repeat;border:none;color:red;}"
                                    "QPushButton:hover{background-image: url(:/1.png);background-repeat: no-repeat;}"
                                    "QPushButton:pressed{background-image: url(:/1.png);}");
    QPushButton *btn2= new QPushButton();
    btn2->setCheckable(true);
    btn2->setFixedSize(btnSize);
    

    /*单选菜单效果*/
    QButtonGroup *buttonGround = new QButtonGroup();
    buttonGround->addButton(btn1);
    buttonGround->addButton(btn2);    
    buttonGround->setExclusive(true);

    /*容器包含*/
    QHBoxLayout *menuLayout = new QHBoxLayout();
    menuLayout->setMargin(0);
    menuLayout->setSpacing(0);
    menuLayout->addWidget(btn1);
    menuLayout->addWidget(btn2);    
    menuLayout->addStretch();

    mainLayout->addLayout(menuLayout);
}

 

 

参考内容:

https://blog.csdn.net/zsy19881226/article/details/77825533

你可能感兴趣的:(嵌入式积累,Qt基础知识,Qt工程应用)