Stefan Monov
Stefan Monov

Reputation: 11732

How is the lifetime of QObjects returned from C++ to QML managed?

I have a QObject subclass (registered with QML) called ToReturn and a QML singleton, defined in C++, called MySingleton. The latter provides this function:

Q_INVOKABLE ToReturn* get_toReturn() {
    return new ToReturn();
}

When I call get_toReturn from QML, am I responsible for later calling destroy() on the returned object? Or is there a way to use automatic memory management for this?

Note that my ToReturn object does not logically belong to an object tree, so I pass nullptr to the parent constructor (QObject's).

Upvotes: 1

Views: 626

Answers (1)

dtech
dtech

Reputation: 49319

It is supposed to work automatically, and objects are supposed to be deleted as soon as they are out of scope, have no parent and no references to them exist.

That being said, there are 2 caveats:

  • objects will rarely be destroyed as soon as the above conditions are met. They tend to linger for quite a while, unless garbage collection is forced

  • in more complex scenarios, objects will be deleted, even if they have parents and references to them. It is a critical bug that's been standing for almost 2 years now, unfortunately with zero work done on it. This has forced me to use manual object lifetime management, setting ownership to CPP explicitly just so objects don't go missing, which simply crashes the application

By default the object returned from your function will have QQmlEngine::JavaScriptOwnership unless you explicitly set it otherwise via:

QQmlEngine::setObjectOwnership(objectptr, QQmlEngine::CppOwnership);

EDIT: Note that the premature deletion has to do with JS ownership, so objects that are declared and created entirely in QML are also subject to it. You can set CPP ownership for such object to protect them too, and deletion of such objects can only be done from C++, preferably using deleteLater().

Upvotes: 1

Related Questions