目標
在使用QRadioButton的時候,期望的方式是將幾個radio button group在一起,對值的read/write都可以按group的方式進行,而不用對單個QRadioButton進行處理。
實現(xiàn)
方式
采用QButtonGroup,用如下步驟實現(xiàn):
- 新建一個QButtonGroup對象;
- 把ui上存在的多個QRadioButton添加到這個QbuttonGroup對象中;
- 對group對象中的每一個radio button設置對應的id,方便后續(xù)read/write時通過id進行;
- 添加group對象的
toggled信號和槽的關聯(lián); - 實現(xiàn)第4步添加的槽函數(shù);
sample code
1. 新建一個QButtonGroup對象
/* RaidoButtonGroup.h*/
QButtonGroup* bgGroup;
/* RadioButtonGroup.cpp constructor*/
bgGroup = new QButtonGroup( this );
2. 把ui上存在的QRadioButton添加到bgGroup中
bgGroup->addButton( ui.rb_0 );
bgGroup->addButton( ui.rb_1 );
bgGroup->addButton( ui.rb_2 );
3. 設置id
bgGroup->setId(ui.rb_0, 0 );
bgGroup->setId( ui.rb_1, 1 );
bgGroup->setId( ui.rb_2, 2 );
4. 添加信號和槽的關聯(lián)
connect( bgGroup, SIGNAL(buttonToggled(int, bool), this, SLOT(on_bgGroup_toggled(int, bool)));
5. 實現(xiàn)槽函數(shù)
void RadioButtonGroup::on_bgGroup_toggled(int id, bool status) {
// id is the QRadioButton id, status is the check status
// or you can get value from bgGroup->checkedId();
qDebug() << bgGroup->checkedId();
qDebug() << id;
}