[Interest] controlling QML singleton lifetime from C++
Ulf Hermann
ulf.hermann at qt.io
Fri Feb 16 20:48:06 CET 2024
Hi Stefan,
> I'd like to be able to replace that singleton instance over the course
> of the application's workflow, but I couldn't find any indication in the
> docs for whether that's allowed, or whether that might lead to undefined
> behaviour.
There is QQmlEngine::clearSingletons(), but it's not for the faint of heart:
> This function drops all singleton instances, deleting any QObjects owned by
> the engine among them. This is useful to make sure that no QML-created objects
> are left before calling clearComponentCache().
>
> QML properties holding QObject-based singleton instances become null if the
> engine owns the singleton or retain their value if the engine doesn't own it.
> The singletons are not automatically re-created by accessing existing
> QML-created objects. Only when new components are instantiated, the singletons
> are re-created.
>
> \sa clearComponentCache()
After this, the engine will have "forgotten" your C++-owned singleton,
and you can delete it, making it null in all properties that still hold
it. Then, if you instantiate a component that uses the singleton, it
will be re-created from your create() function.
If you just delete the singleton without clearSingletons() you've
created a null singleton. There is code that should deal with that case,
but I don't think it's exercised very often.
best regards,
Ulf
More information about the Interest
mailing list