Search code examples
c++qtqlabelqlist

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


Solution

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