Order of multiple C++ QML_ELEMENT instantiation
-
I am learning Qt 6 Quick for about a month now. I have the following classes:
class Class1 : public QObject { Q_OBJECT Q_SINGLETON Q_ELEMENT .... }; class Class2 : public QObject { Q_OBJECT Q_SINGLETON Q_ELEMENT .... };I understand that when using qmlRegisterSingletonInstance or other methods specified in main.cpp
// main.cpp ... Class1 instance1; Class2 instance2; qmlRegisterSingletonInstance("MyObject1", 1, 0, "MyApi1", instance1.get()); qmlRegisterSingletonInstance("MyObject2", 1, 0, "MyApi2", instance2.get()); ...I can specify the order of the instantiations.
How about when using macro QML_ELEMENT and QML_SINGLETON? Are they instantiated in the order of files inclusion in CMakeLists.txt qt_add_qml_module ? or does it happen during import statements in qml file?
-
Consider the order to be undefined, and something you shouldn't rely on. To be honest, that's the same as if you were to use
qmlRegisterSingletonTypeusing the imperative API; there's no instantiation at the point of the registration, that will happen later when the engine actually needs the singleton (and "needs" is intentionally vague here).If you have an order-dependent construction, you should (in that order of preferability)
a) consider if you can move away from that pattern, or
b) use https://doc-snapshots.qt.io/qt6-dev/qqmlengine.html#setExternalSingletonInstance once 6.12 is released or
c) keep using imperative registration.