Create Singleton usable in c++ & qml
-
wrote on 17 Jun 2024, 08:04 last edited by
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. -
wrote on 17 Jun 2024, 09:13 last edited by
You should probably use
qmlRegisterSingletonInstance
or maybeqmlRegisterSingletonType
rather than theQML_SINGLETON
macro. I think this will give you the control you need. -
wrote on 18 Jun 2024, 12:37 last edited by Johan_R
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. -
wrote on 18 Jun 2024, 13:03 last edited by
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
-
wrote on 19 Jun 2024, 09:02 last edited by
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?
1/5