Details
-
Suggestion
-
Resolution: Unresolved
-
P2: Important
-
None
-
None
Description
https://doc.qt.io/qt-6/qqmlengine.html#QML_SINGLETON says:
By default, each QQmlEngine will try to create a singleton instance using either the type's default constructor or a static factory function of the signature T *create(QQmlEngine *, QJSEngine *) when the type is first accessed. If both do exist and are accessible, the default constructor is preferred.
The current approach requires the user to have a dummy argument in the type's constructor if they also want to use Q_GLOBAL_STATIC, otherwise the QML engine creates a separate singleton, resulting in two instances and some interesting debugging sessions. Making the default constructor inaccessible isn't an option because Q_GLOBAL_STATIC needs it. See the attached example for a demonstration of this, where two singletons are created.
It would be better if the create function would be used instead of the default constructor if it's available. It is there for a very specific purpose, so it makes sense that it takes priority. This allows users to use Q_GLOBAL_STATIC and not have duplicate singleton instances.