PDA

View Full Version : Can I Choose the label on runtime?



akrep55tr
13th February 2011, 18:15
Should I choose the label or other ui object before runtime? Can I choose them on runtime?

What I mean is :

Should I write:


for (int i = 0; i < 5 ; i++)
{
ui->label_0->setText(QString::number(i));
ui->label_1->setText(QString::number(i));
ui->label_2->setText(QString::number(i));
ui->label_3->setText(QString::number(i));
ui->label_4->setText(QString::number(i));

}


But I want to write as:



for (int i = 0; i < 5 ; i++)
{
ui->label_(i)->setText(QString::number(i));

}


Is it possible to write in this way?

tbscope
13th February 2011, 18:56
You can't do it like you wrote it.

But, there are a couple of techniques that do let you do this.

1. Use the name of the object.
2. Create a list of objects.

high_flyer
13th February 2011, 18:59
EDIT:
oops, beat to it by tbscope.

No this is not possible the way you wrote it, as you will find out if you try to compile it.
What you can do is put all your labels in a container:


QVector<QLabel*> vecLabels;
vecLabels.push_back(ui->label_0);
vecLabels.push_back(ui->label_1);
...
for (int i = 0; i < 5 ; i++)
{
vecLabels.at(i)->setText(QString::number(i));

}

akrep55tr
13th February 2011, 19:30
@tbscope , @high_flyer
Thank you for your replies.

@high_flyer
Thank you for your example, it helped a lot.