[solved] catching toggle signal from bunch of QCheckBoxes ?
-
Hello,
i have a bunch of QCheckboxes and put them into a QVector so i can access them
easily in a for loop.
In which kind of Container or Group/ Frame widget i should pack these Checkboxes
to get a signal when any of them got toggled ?
thanks !void SetLogLevelDlg::on_pushButton_clicked() { QVector<QCheckBox*> chkBits; chkBits.push_back(ui->chkb_0); chkBits.push_back(ui->chkb_1); chkBits.push_back(ui->chkb_2); chkBits.push_back(ui->chkb_3); chkBits.push_back(ui->chkb_4); chkBits.push_back(ui->chkb_5); chkBits.push_back(ui->chkb_6); chkBits.push_back(ui->chkb_7); quint8 result = 0; for(int i=7; i>0; --i) { result = result | chkBits[i]->isChecked(); result = result << 1; } result = result | chkBits[0]->isChecked(); ui->lb_result->setText(QString::number(result)); }
-
Use QSignalMapper.
-
I'd use QButtonGroup. This is only for handling events from the group of buttons, and not for the layout of them in your GUI.
-
Seems i got a satisfying solution, any critics highly welcome:
Advantage of the QButtonGroup-approach is e.g. "setExclusive"
(Maybe helpful for others)header:
private slots: void chkBox_clicked(int, bool); private: Ui::MainWindow *ui; QCheckBox** chkBoxes; QButtonGroup *butGrp; QCheckBox* chkBox;
source:
- ui->VL_1 is a QVBoxLayout placed on fresh Form in Designer
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); chkBoxes = new QCheckBox*[8]; butGrp = new QButtonGroup(this); for(int i=0; i<8; i++) { chkBox = new QCheckBox(QString("bit_%1").arg(i), this); chkBox->setObjectName(QString("bit_%1").arg(i)); ui->VL_1->addWidget(chkBox); chkBoxes[i] = chkBox; butGrp->addButton(chkBoxes[i], i); } butGrp->setExclusive(false); connect(butGrp, SIGNAL(buttonToggled(int,bool)), this, SLOT(chkBox_clicked(int, bool))); } void MainWindow::chkBox_clicked(int _id, bool _b) { qDebug() << __FUNCTION__ << __LINE__ << _id << chkBoxes[_id]->objectName() << _b ; chkBoxes[_id]->setText("marked"); }
-
You can also do something different i.e. connect every checkbox (signal toggled(bool) to same slot and inside such slot just do:
connect (ui->checkBox_1, SIGNAL(toggled(bool)), this, SLOT(checkBoxToggled(bool))); connect (ui->checkBox_2, SIGNAL(toggled(bool)), this, SLOT(checkBoxToggled(bool)));
Then in slot:
QCheckBox *box = static_cast<QCheckBox*>( this->sender()); if (state) { qDebug() << "Checked:" << box->objectName(); }
That way You will still get access to the object. To i.e. uncheck all others You could use container -> findChildren<QCheckBox *>(); and uncheck all others. Of course above suggestions are still valid and in the end it all depends on Your need.
I personally wouldn't store list to Ui Widgets. I tend to create all my Ui's in QtDesigner and not by code so my above solution will give more flexibility.