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) {
     Q_UNUSED(engine)
     Q_UNUSED(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 ?

    Thanks,
    Gianluca.



  • Hi Gianluca,

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

    Thanks,
    Thawfeek.



  • @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" (http://doc.qt.io/qt-5/qtqml-cppintegration-definetypes.html#registering-c-types-with-the-qml-type-system)? Could you replace it with just an object set as a context property?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.