Search code examples
c++qtqmlqt4qt5

How can I get a QObject's children?


I am trying to get the children of the a QObject class and add their data to the parent (see QML example below). However, when I call the following code in the constructor, it returns no children. It appears that the child list has not yet been populated. It works if I place the same code in the paint() function, but I need the data earlier than that.

MultiGauge::MultiGauge() : 
    QQuickPaintedItem()
{
    QObjectList children = this->children();

    for (int i = 0; i < children.length(); i++)
    {
        this->myQList.append(children[i]->metaObject()->className());
    } 
}

Here is the QML file

MultiGauge {

    height: 125
    width: height
    Limits {
        min: 0
        caution: 1250
        max: 2000
    }
    Limits {
        min: 100
        caution: 200
        max: 300
    }
}

EDIT: Solution:

MultiGauge::componentComplete()
{
    // must call the parent's version of the function first
    QQuickPaintedItem::componentComplete();

    // now we can do what we need to
    QObjectList children = this->children();

    for (int i = 0; i < children.length(); i++)
    {
        this->myQList.append(children[i]->metaObject()->className());
    } 
}

Solution

  • You should delay the iteration until the QML object tree is completed. You can that by using

    MultiGauge {
      // ...
      Component.onCompleted: doSomeStuff()
    }