0

I want to add checkboxes dynamically. I found some links helpfull ,but each of them has a problem that I can't solve.

for example in this link we can create & add QCheckBoxes dynamically, but I can't access them out of their definition scope (for).

And another way is using QListWidgetItem with setCheckState. but It has a very big problem! when I click on the CheckState, it doesn't notice it and just focus on the Item that is focus is on it!!!! {in these links this problem is introduced but no solution: this and this }

Is there any way to add Chekboxes dynamically that I can access them and their checkstate out of their definition scope?

Community
  • 1
  • 1
s.m
  • 209
  • 2
  • 7
  • 17

1 Answers1

1

You need to save pointers to checkBoxes that you've created. For example to add QVector<QCheckBox> checkBoxes; to your widget and then append this pointers to vector.

Result code can look like this:

In header:

YourWidget : public QWidget {
....
QVector<QCheckBox*> checkboxes;
....

And in the source:

for (int i = 0; i < 5; i++) {
    QCheckBox *box = new QCheckBox;
    layout->addWidget(box);
    checkboxes.append(box);
}

So then you can get acces to your checkBoxes: checkboxes[0]->setChecked(true); or smth

And don't forget to release memory allocated for checkBoxes in destructor of you widget (you don't need to do this if you added them to layout)

for (int i = 0; i < checkboxes.size(); i++) {
    delete checkboxes[i];
}
Tony O
  • 513
  • 4
  • 12
  • 1
    You don't have to delete the objects in the destructor. They are automatically destroyed by Qt if you add them to a layout. – thuga Jan 25 '16 at 09:58
  • in line: checkboxes.append(box); – s.m Jan 25 '16 at 10:20
  • there is no such a property fir checkboxes[0]. { checkboxes[0]->value() } – s.m Jan 25 '16 at 10:21
  • forgot astersisk in QVector Value was only for example. You need to call one of checkBoxes methods, like setChecked. Edited the answer. – Tony O Jan 25 '16 at 10:25