如何获得 QObject 的 children?

How can I get a QObject's children?

我正在尝试获取 QObject class 的 children 并将其数据添加到 parent(参见下面的 QML 示例)。但是,当我在构造函数中调用以下代码时,它 returns 没有 children。 child 列表似乎尚未填充。如果我在 paint() 函数中放置相同的代码,它会起作用,但我需要比那更早的数据。

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

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

这是 QML 文件

MultiGauge {

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

编辑:解决方案:

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());
    } 
}

您应该延迟迭代,直到 QML 对象树完成。你可以通过使用

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