[Interest] controlling QML singleton lifetime from C++

Stefan Seefeld stefan at seefeld.name
Fri Feb 16 21:16:31 CET 2024


Hi Ulf,

thanks for the prompt reply !
So for avoidance of doubt: none of the objects for which the
`QJSEngine::CppOwnership` flag is set will actually be deleted, right ?
Rather, only any QML references will be cleared, so the next access will
have to call my `create()` function again.

If that's the case, that doesn't sound too bad, so long as all my
singletons are indeed owned by the C++ runtime. It would be even better if
there was a `clearSingleton(instance)` function that would only clear a
single instance, and thus avoid any risk of undesired side-effect.

Many thanks,


On Fri, Feb 16, 2024 at 2:50 PM Ulf Hermann via Interest <
interest at qt-project.org> wrote:

> 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
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest
>


-- 

      ...ich hab' noch einen Koffer in Berlin...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20240216/3826ca6d/attachment.htm>


More information about the Interest mailing list