Important: Please read the Qt Code of Conduct -

Is there any way to change QJSEngine object ownership?

  • Good day!

    I'm developing an application with wide scripting capabilities using QJSEngine as JS script engine.
    There is singleton class (inherited from QObject, and NULL parent) that needs to be available from multiple instances of QJSEngine class.

    If I bind my singleton class instance to one of the JS engine instance like this:

    @auto jsSingleton = _jsEngine.newQObject(Singleton::instance());
    _jsEngine.globalObject().setProperty("singleton", jsSingleton );@

    then my singleton class instance will be deleted during corresponding QJSEngine destructor.

    Is there any way to prevent it, like explicitly set JS engine object ownership to CppOwnership?

  • It looks like I found an answer, but it's kinda strange.

    1. include <QQmlEngine> instead of <QJSEngine>
    2. after setting property of global object call this:
      @QQmlEngine::setObjectOwnership(Singleton::instance(), QQmlEngine::CppOwnership);@

    And now my singleton object is not deleted.

    It looks like this method should be moved from QQmlEngine to QJSEngine, because it internally uses only QQmlData object and has nothing specific to QQmlEngine.

Log in to reply