[Interest] sharing singleton instance between C++ and QML

Ulf Hermann ulf.hermann at qt.io
Thu Oct 26 08:50:54 CEST 2023


The very common misconception I keep reading over and over is that C++ 
singletons should be the same as QML singletons. They generally aren't. 
You can shoehorn a C++ singleton into a QML one, but if you can avoid 
that exercise, you should avoid it.

The usual way to declare a QML singleton is just the same as any old QML 
object type: You write a QObject-derived class with a number of 
properties and invokable methods. You make sure it has a default 
constructor the QML engine can use, and you add QML_ELEMENT. Then you 
add QML_SINGLETON in addition. That's it. Each QML engine will create at 
most one instance of this type. Yes, there can be more than one instance 
in total if there is more than one engine. Yes, the QML engine 
absolutely wants to own your singleton. And that saves _you_ headaches 
because now you don't have to care about your singleton's life cycle 
vis-a-vis the various engines that may be messing with it.

If you have some actually singular data you want to serve from your 
singleton you still can. Your singleton object can keep a pointer to the 
singular data and return it from its property getters or manipulate it 
from its invokable methods.

Now, as always, you _can_ shoot your foot if you really want to. Here is 
how you find the gun: If your singleton does not have a default 
constructor the engine can use, but the engine instead finds a static 
method "Foo *create(QJSEngine *, QQmlEngine *)", it will use that to 
obtain the singleton. The method can also be defined on the QML_FOREIGN 
wrapper in case you cannot touch the actual class at all. In that method 
you can go to town with your singleton. You can create it on the fly or 
retrieve it from somewhere. You can declare its object ownership. You 
can decide yourself which object to return for which engine. You should 
probably check if the thread affinity matches, but if you don't, it's 
your problem.


More information about the Interest mailing list