Vinay Kulkarni
Vinay Kulkarni

Reputation: 85

What is the correct method to get all QLabels form UI in QList?

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

Upvotes: 3

Views: 1344

Answers (2)

CapelliC
CapelliC

Reputation: 60034

findChildren should do exactly that: try

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

labelList = findChildren<QLabel*>();

to be executed in a QWidget derived object

Upvotes: 3

Nejat
Nejat

Reputation: 32665

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)
{
  ...
}

Upvotes: 6

Related Questions