QPushButton实现两个按钮互斥同时这两个按钮与其他按钮互斥

总结:
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);

}
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值