PDA

View Full Version : Iterate through set of components



QTie
15th June 2011, 07:48
Hello. I have following components on my MainWindow ui: groupBox1, label1, button1.

Problem is that I need to set some properties at the same time to groupBox1, label1, button1 and groupBox2, label2 etc
Is there a way or iterator (foreach, for) to do this by changing the index number of the components. Thanks.


int i = 1;

ui->groupBox[i]->setEnabled(true);
ui->label[i]->setText("some text");
----------------------
current code:
ui->groupBox1->setEnabled(true);
ui->label1->setText("some text");

franz
15th June 2011, 07:53
Generated code cannot do that for you. You would have to code the ui yourself to have readily available arrays or lists with the widgets. However, there is another approach:

foreach (QGroupBox *box, findChildren<QGroupBox*>())
box->setEnabled(true);
foreach (QLabel *label, findChildren<QLabel *>())
label->setText("some text");


You might need to filter a bit more though.

Santosh Reddy
15th June 2011, 08:01
If you are using Qt Designer to create the components, then accessing by name is only option.

If you create in your code, then you can store the list if widgets in a list, vector ( eg.g QList<QLabel*>...) then use them later to change the properties. Remember you only store the pointers of the widgets, you should not delete them, they are owned by the MainWindow, it will take care of deleting them, so don't use this list after MainWindow is done.