How to refer to labels created in a for loop?
-
Hi.
I am creating multiple instances of labels in a for loop, and displaying them.
I want to ask, how can I refer to a particular label I create in the loop? Because I don't know their object name. How can I work with a specific label if I want to?
-
Store them in a container or let Qt collect them with QObject::findChild()
-
@Christian-Ehrlicher
Thanks for your answer. I wanted to request an example of storing the labels in a container or collecting them in findChild().Thank you.
-
@BigBen said in How to refer to labels created in a for loop?:
I wanted to request an example of storing the labels in a container or collecting them in findChild().
Why? This is basic c++ stuff which you should know. for findChild() there is even an example in the link I gave you...
-
QLabel* label_one = new QLabel("label", parent);
Viola! you have a handle to your label.
-
- Store them in a container yourself as you create them:
QList<QLabel *> labels; for (int i = 0; i < 10; i++) { QLabel *label = new QLabel; someLayout->addWidget(label); labels.append(label); }
- Assign them an
objectName
for future reference to recall an individual one:
QList<QLabel *> labels; for (int i = 0; i < 10; i++) { QLabel *label = new QLabel; label->setObjectName(QString("label_%1").arg(i)); someLayout->addWidget(label); } QLabel *label_2 = someParentWidget->findChild<QLabel *>("label_2");
- Collect them all via
findChildren()
:
QList<QLabel *> labels = someParentWidget->findChildren<QLabel *>();
1/6