Create Singleton usable in c++ & qml
-
I have a Logger class. This class should be available from C++ and Qml and should be a singleton.
All preparations likeQML_SINGLETON
etc. are made.How can I create my Logger singleton in my
main.cpp
and use the same instance in myapplication.qml
?
My Logger is running in its own thread. -
First you define the singleton in C++. The best way is to use the Meyer's Singleton pattern. Do not use
QML_SINGLETON
. Then you export the singleton to QML by calling qmlRegisterSingletonInstance() in yourmain()
function. -
QML singletons are not the same as C++ singletons. The most important difference is that each QML engine gets its own instance of each singleton. It has been like that since the introduction of singletons in QML. The qmlRegisterSingletonInstance() method was mistake because it doesn't (and cannot) specify the engine the singleton instance belongs to. We shouldn't have added it. There is one way to work around this if you have only a single engine: https://doc.qt.io/qt-6/qml-singleton.html#exposing-an-existing-object-as-a-singleton
-
I am still using Qt 5 and am trying to adopt the modern approach and move away from context properties - it seemed that this is what we are encouraged to do. However, this issue with
qmlRegisterSingletonInstance
does not appear to have been explained in the Qt 5 documentation. Having tried to do the right thing, it appears that I am now faced with new complications that are emerging out of the woodwork.If we shouldn't use
qmlRegisterSingletonInstance
, how are we supposed to provide the dependencies needed by the C++ object? That is, if I want to expose a C++ object as a QML singleton, and it doesn't make sense to default construct that object, what is the recommended approach?