Search code examples
qtcheckboxdynamicqcheckbox

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


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?


Solution

  • 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];
    }