View Full Version : for loop application
cooper
1st February 2011, 00:35
Hi everyone,
I have a question about the for() loop function in Qt.
in my program, i have 10 labels, which indicate 10 led lights.
I can change the color for each label by using:
ui->label_led_1->setPixmap(picLedRed);
ui->label_led_2->setPixmap(picLedRed);
...
I wonder how can i use the For() loop to simplify the code.
ex:
for (int i = 1; i <=10; i ++)
ui->label_led_i->setPixmap(picLedRed);
Can any one tell me how i can increment the label number i, please?
Thanks in advance.
helloworld
1st February 2011, 01:39
Try this:
for (int i = 1; i <= 10; i++)
{
QLabel *label = qFindChild<QLabel *>(this, "label_led_" + QString::number(i));
if (label) { label->setPixmap(picLedRed); }
}
Edit: (or replace 'this' with a pointer to the MainWindow if the loop is in another class)
tbscope
1st February 2011, 05:27
Or put your labels in a list.
example:
QList<QLabel*> myLedLabels;
myLedLabel->append(ui->label_led_1);
// do append for all your led labels
for (int i = 0; i < 10; ++i)
{
myLedLabels.at(i).setPixmap(picLedRed);
}
Lykurg
1st February 2011, 06:14
I would probably also take the way with qFindChild. But to avoid to call qFindChild ten times, one could use
QList<QLabel*> labels = qFindChildren<QLabel*>(this, QRegExp("^label_led_[0-9]+$"));
wysota
1st February 2011, 08:40
If I have 10 labels added with designer then I would construct a function or a macro and copy&paste the code ten times instead of creating artificial lists. Unless of course you intend to reuse the list multiple times for other purposes.
stampede
1st February 2011, 08:42
Another way (if you have numbered your labels starting from 0):
#include <boost/preprocessor.hpp>
#define TO_REPEAT(z,count,action) _ui->label_led_ ## count -> action ;
// and use it like:
QPixmap pixmap(":/pic.jpg");
BOOST_PP_REPEAT(10, TO_REPEAT, setPixmap(pixmap) );
// expands to :
_ui->label_led_0->setPixmap(pixmap);
_ui->label_led_1->setPixmap(pixmap);
// ...
_ui->label_led_9->setPixmap(pixmap);
cooper
1st February 2011, 19:34
Thanks for you all. I really appreciate you guys' help. I will give it a try :)
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.