可以通过一个简单的测试来验证对象创建的顺序。
class Test : public QQuickItem {
Q_OBJECT
public:
Test(QQuickItem * p = 0) : QQuickItem(p) { qDebug() << this; }
};
然后:
Test {
objectName: "a"
Component.onCompleted: console.log(objectName, this)
Test {
objectName: "b"
Component.onCompleted: console.log(objectName, this)
Test {
objectName: "c"
Component.onCompleted: console.log(objectName, this)
}
Test {
objectName: "d"
Component.onCompleted: console.log(objectName, this)
}
}
Test {
objectName: "e"
Component.onCompleted: console.log(objectName, this)
}
}
输出如下:
Test(0x6a7378, parent=0x0, geometry=0,0 0x0)
Test(0x6a73d8, parent=0x0, geometry=0,0 0x0)
Test(0x6a7438, parent=0x0, geometry=0,0 0x0)
Test(0x6a7498, parent=0x0, geometry=0,0 0x0)
Test(0x6a74f8, parent=0x0, geometry=0,0 0x0)
qml: a Test(0x6a7378, "a")
qml: e Test(0x6a74f8, "e")
qml: b Test(0x6a73d8, "b")
qml: d Test(0x6a7498, "d")
qml: c Test(0x6a7438, "c")
这表明对象构造函数确实被称为自下而上。
另请注意,onCompleted 的顺序不同,具体取决于该处理程序的安装位置。如果您像这样将Test 包裹在Obj.qml 中:
Test {
id: rectangle
Component.onCompleted: console.log(objectName, this)
}
并像这样声明结构:
Obj {
objectName: "a"
Obj {
objectName: "b"
Obj {
objectName: "c"
}
Obj {
objectName: "d"
}
}
Obj {
objectName: "e"
}
}
然后你会得到一个一致的“从后到前”的输出,这是你在第一个场景中没有得到的:
Test(0x4b2458, parent=0x0, geometry=0,0 0x0)
Test(0x4b24b8, parent=0x0, geometry=0,0 0x0)
Test(0x4b2518, parent=0x0, geometry=0,0 0x0)
Test(0x4b2578, parent=0x0, geometry=0,0 0x0)
Test(0x50f9d68, parent=0x0, geometry=0,0 0x0)
qml: e Test(0x50f9d68, "e")
qml: d Test(0x4b2578, "d")
qml: c Test(0x4b2518, "c")
qml: b Test(0x4b24b8, "b")
qml: a Test(0x4b2458, "a")
然而,这一切都反映了对象创建的顺序,而不是对象完成的顺序,这涉及到一堆其他的东西,可以以任意顺序执行,具体取决于绑定表达式结构。
简而言之,你不应该真的依赖那个顺序,如果你这样做了,你就做错了。你不应该依赖任何比整个 QML 源代码树完成更精细的东西,qtquick 引擎本身会注意延迟绑定表达式的 初始化 等,直到整个对象树完成,所以你不会'没有问题,它会自动发生,但是依赖任何较低级别和更细粒度的东西是设计中的潜在缺陷,应该避免。如果您想要更明确的初始化顺序,请给您的对象 ID,并为整个 qml 文件执行一个初始化表达式,该表达式将所有内容连接在一起。该表达式中的语句将按照它们定义的顺序执行。