Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Reload QML Singleton instances



  • Hello,

    Is it possible to reload a past singleton instance with qmlRegisterSingletonType and use the new instance in QML?

    Exemple :

    // allocate example before the engine to ensure that it outlives it
    QScopedPointer<SingletonTypeExample> example(new SingletonTypeExample);
    QQmlEngine engine;
    
    // Third, register the singleton type provider with QML by calling this
    // function in an initialization function.
    qmlRegisterSingletonInstance("Qt.example.qobjectSingleton", 1, 0, "MyApi", example.get());
    
    engine.load("qrc:/MyApp.qml");
    
    example.reset(new SingletonTypeExample);
    

    I've already tried it and the object becomes undefined once it has been reset.

    Thank you


  • Qt Champions 2018

    No it is not trivially possible.

    Even it if was your solution wouldn't work, you are resetting the scoped pointer but the qml engine is not aware of it, it only knows the raw pointer you passed to it and which you destroyed later when you resetted the scoped pointer.

    What you could do is expose a singleton with a myApi property, and when you want to change the myApi, do it and emits its notify signal.

    Alternatively you could reevaluate your needs. Why do you need to reload a singleton? That seems weird on a first look.


  • Qt Champions 2018

    No it is not trivially possible.

    Even it if was your solution wouldn't work, you are resetting the scoped pointer but the qml engine is not aware of it, it only knows the raw pointer you passed to it and which you destroyed later when you resetted the scoped pointer.

    What you could do is expose a singleton with a myApi property, and when you want to change the myApi, do it and emits its notify signal.

    Alternatively you could reevaluate your needs. Why do you need to reload a singleton? That seems weird on a first look.



  • Thank you for your response.

    I need to pass an instance of an object in QML and this instance can be replaced by another one in a particular situation.

    I found a way to do this by passing my instance through the QML context.


Log in to reply