C++ 如何获得QObject';谁的孩子?

C++ 如何获得QObject';谁的孩子?,c++,qt,qml,qt4,qt5,C++,Qt,Qml,Qt4,Qt5,我试图获取QObject类的子类,并将它们的数据添加到父类中(请参见下面的QML示例)。但是,当我在构造函数中调用以下代码时,它不会返回任何子级。子列表似乎尚未填充。如果我在paint()函数中放置相同的代码,它会起作用,但我需要早于此的数据 MultiGauge::MultiGauge() : QQuickPaintedItem() { QObjectList children = this->children(); for (int i = 0; i <

我试图获取
QObject
类的子类,并将它们的数据添加到父类中(请参见下面的QML示例)。但是,当我在构造函数中调用以下代码时,它不会返回任何子级。子列表似乎尚未填充。如果我在
paint()
函数中放置相同的代码,它会起作用,但我需要早于此的数据

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

    for (int i = 0; i < children.length(); i++)
    {
        this->myQList.append(children[i]->metaObject()->className());
    } 
}
编辑:解决方案:

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());
    } 
}
MultiGauge::componentComplete()
{
//必须首先调用父函数的版本
QQuickPaintedItem::componentComplete();
//现在我们可以做我们需要做的
QObjectList children=此->子对象();
for(int i=0;imyQList.append(children[i]->metaObject()->className());
} 
}

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

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

我相信当为父级调用构造函数时,不应该有子级。应该在构建父级之后添加子级。@drescherjm是的,但是之后如何正确捕获这些子级<代码> CyrDeNeTeNe:(代码)>似乎没有触发我在父母不知道他有孩子的时候,你需要在需要时得到它们。试着从QML中从C++中调用C++函数。这就是我一直在寻找的解决方案。也适用于小部件和QObject。
MultiGauge {
  // ...
  Component.onCompleted: doSomeStuff()
}