How to manage lifetime of dynamically allocated QObject derived objects passed to QML?
-
I have this code:
@QVariant componentFromCode(QString code) {
QQmlComponent * component = new QQmlComponent(engine);
engine->setObjectOwnership(component, QQmlEngine::JavaScriptOwnership);
connect(component, &QQmlComponent::destroyed, this, &Factory::echo);
component->setData(code.toUtf8(), QUrl());
return QVariant::fromValue(component);
}@However, the echo slot is never called, therefore the object is never deleted. The object can be deleted if destroy() is called explicitly, but it is really not convenient and not always possible to use, the lifetime should be managed automatically, i.e. whenever the object falls out of scope or if a property, whenever the object gets destroyed.
Any ideas?
-
Hi,
I looked into this a bit. And couldn't reproduce an example, where a small C++ defined class created dynamically from JS ever get handled by the garbage collection. I'm sure it happens, but its not that predictable. I used debug printing in the destructor and never saw it before application closing.
What is the problem you're trying to solve with this? If you leave pointer dangling, it usually means you're not interested in it anymore. If you're worried about the memory, then I guess the gc will kick in when needed or you need that explicit destruction.
-
What worries me is the fact the echo() slot is never triggered. Not even as the application is closed. This leads me to believe such objects returned to QML are practically leaking, and I am not a big fan of believing somehow this is not the case. I don't like memory leaks. And somehow QML seems to be full of those. I've already encountered situations where QML doesn't release resources and memory usage climbs to hundreds of MB and never drops down.