Important: Please read the Qt Code of Conduct -

Sharing a singleton object in C++ and QML: am I on the right way ?

  • Dear all,
    I need to share a singleton object both in C++ and QML. Hence, there is only one instance of an object that can be accessed from C++ side and from QML script.
    For doing so, I registered the singleton object using the qmlRegisterSingletonType and implemented the singleton provider function returning the instance that I use on C++ side.
    That's the code:

    QObject* QFacebook::qFacebookProvider(QQmlEngine *engine, QJSEngine *scriptEngine) {
     return QFacebook::instance();
    QFacebook* QFacebook::instance() {
     static QFacebook* facebook = new QFacebook();
     return facebook;

    But, I don't know if in this way I can break some rules about QML object allocation. In the documentation is clearly stated that the object returned by singleton provider is owned by QML. So, this imply that QML may destroy the singleton instance ? If so, why QML should destroy a singleton ?
    What are the problems of having a singleton instance owned by QML and shared into C++ side ?


  • Hi Gianluca,

    Have you got any solution to your problem? I am facing exactly the same issue.


  • @TopNotch_Mach07 First make sure you really need such a singleton. Do your requirements include something mentioned in "Registering Singleton Objects with a Singleton Type" ( Could you replace it with just an object set as a context property?

Log in to reply