Search code examples
c++qtqobjectqcheckboxqtwidgets

QCheckbox name access


I generate checkboxes as follows:

foreach(QString filt, types){
    QCheckBox *checkbox = new QCheckBox(filt, this);
    checkbox->setChecked(true);
    vbox->addWidget(checkbox);
}

I need to get access to these checkboxes by name but they are all called the same?

I need to read the text they display.

How can I go about this?

Is it possible to run a for loop and attach the value of i onto the end of the checkbox. So in effect, the checkbox would be called checkbox[0], checkbox [1], etc?

EDIT:

I've changed the code to the following:

for(int i=0; i<types.count(); ++i)
{
    QString filt = types[i];
    *checkboxCount = *checkboxCount + 1;
    QCheckBox *typecheckbox[i] = new QCheckBox(filt, this);
    typecheckbox[i]->setChecked(true);
    vbox->addWidget(typecheckbox[i]);
}

I thought this was a way to dynamically name the checkboxes so I can loop through them to get the text value from them.

I'm getting the error 'variable-sized object may not be initialized' on this line QCheckBox *typecheckbox[i] = new QCheckBox(filt, this);

Any ideas to a solution/ alternate approach?


Solution

  • If you want to access the checkboxes later, you can just use the find children method as follows:

    QStringList myStringList;
    QList<QCheckBox *> list = vbox->findChildren<QCheckBox *>();
    foreach (QCheckBox *checkBox, list) {
        if (checkBox->isChecked())
            myStringList.append(checkBox->text());
    }