3
QList<QLabel> labelList;

foreach (QLabel lbl, ui)
{
    labelList.append(lbl);
}

I wanted to add all QLabels in the QList, above code generates an error, please help

Nejat
  • 31,784
  • 12
  • 106
  • 138
Vinay Kulkarni
  • 81
  • 1
  • 10

2 Answers2

6

You can get the list of pointers to the child widgets using QList<T> QObject::findChildren ( const QString & name = QString() ). If ui belongs to a QMainWindow, it could be done by:

QList<QLabel *> list = ui->centralWidget->findChildren<QLabel *>();

To find children of non-QMainWindow containers, such as QDialog or QWidget, use:

QList<QLabel *> list = this->findChildren<QLabel *>();

Now you can iterate through the list like:

foreach(QLabel *l, list)
{
  ...
}

Or, in C++11:

for(auto l : list)
{
  ...
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Nejat
  • 31,784
  • 12
  • 106
  • 138
3

findChildren should do exactly that: try

QList<QLabel*> labelList;  // note the pointer!

labelList = findChildren<QLabel*>();

to be executed in a QWidget derived object

CapelliC
  • 59,646
  • 5
  • 47
  • 90