总结:
1:使用QButtonGroup,使用setExclusive设置为true,组内仅有一个按钮被选中,实现两个按钮互斥
2:QPushButton 可以通过setChecked来设置自身状态,是否处于按下状态
3,添加到QButtonGroup的中按钮,当setExclusive设置为true,当其中一个按钮按下,以后组中始终由于按钮被setChecked为true,这也是组中互斥的原因。
4,为使组中按钮与其他按钮互斥,就需要先关闭互斥属性,即:setExclusive设置为false,然后在关闭每个按钮被checed的数据,即:setChecked为false。最后在setExclusive设置为true,保证组中元素依然具有互斥功能。
//实现代码
1:使用设计师 添加buttona、buttonb和buttonc三个按钮
putton.h
class putton : public QMainWindow
{
Q_OBJECT
public:
putton(QWidget *parent = Q_NULLPTR);
public slots:
//用于与其他按钮互斥的槽函数
void buttona_breturn(void);
private:
Ui::puttonClass ui;
//组对象
QButtonGroup * box;
};
putton.cpp
putton::putton(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
box = new QButtonGroup;
//这里设置按钮样式,便于观察,未按下:yellow。按下:red
ui.buttona->setStyleSheet("QPushButton{background-color:yellow;}QPushButton:checked{background-color:red;}");
ui.buttonb->setStyleSheet("QPushButton{background-color:yellow;}QPushButton:checked{background-color:red;}");
ui.buttonc->setStyleSheet("QPushButton{background-color:yellow;}QPushButton:checked{background-color:red;}");
//添加QPushButton到QButtonGroup
box->addButton(ui.buttona);
box->addButton(ui.buttonb);
//QButtonGroup设置组内元素互斥
box->setExclusive(true);
///对了,这里设置QPushButton未切换模式,我感觉好控制些
ui.buttona->setCheckable(true);
ui.buttonb->setCheckable(true);
//其他按钮的槽函数,实现与其他按钮互斥
connect(ui.buttonc, &QPushButton::clicked, this, &putton::buttona_breturn);
}
///槽函数
void putton::buttona_breturn(void)
{
//这就不写注释了,上面总结有
box->setExclusive(false);
ui.buttona->setChecked(false);
ui.buttonb->setChecked(false);
box->setExclusive(true);
}