> Sent: Monday, May 10, 2021 at 3:08 AM
> From: "Ulf Hermann" <ulf.herm...@qt.io>
> To: interest@qt-project.org
> Subject: Re: [Interest] QML Singleton and QTimer?
>
> Hi,
>
> > GuiApplication::GuiApplication(int argc, char*argv[]):
> >     QGuiApplication::QGuiApplication(argc, argv)
> > {
> >     m_hardwareInterface = new HardwareInterface;
> >     qmlRegisterSingletonInstance("com.company", 1, 0, "HardwareInterface", 
> > m_hardwareInterface);
> > }
>
> qmlRegisterSingletonInstance() is dangerous if you create your singleton
> in a different thread than the one the QML engine runs on. The QML
> engine expects to be able fiddle with internals of those objects via the
> metaobject system.
>
> It also does surprising things when you have multiple QML engines: The
> first one to access it grabs the objects and all others only see null.
>
> It also does not play ball with qmlRegisterTypesAndRevisions() the way I
> had intended. You cannot register an instance before the type because
> the type will then get rejected. You also cannot register an instance
> after the type because there is no way to hook into the type
> registration procedure without providing some kind of callback. If you
> could provide a callback, then that would be pretty much the same as
> providing a factory function, though.
>
> The whole qmlRegisterSingletonInstance() was a mistake, sorry about
> that. It's too easy to shoot yourself in the foot with it and there is
> no way to make its type visible at compile time. You should really use
> the QML_SINGLETON macro and let the QML engine handle the life cycle of
> the object. The QML engine will make sure to create and destroy it on
> the right thread. qmlRegisterSingletonInstance() will be deprecated
> before Qt 7.

It definitely seems that way! I hope this can be added to the documentation to
avoid other people going down this path? I was eager to finally use it, as it
would have simplified things on my side. But it looks like it is a difficult
thing to wield properly.


_______________________________________________
Interest mailing list
Interest@qt-project.org
https://lists.qt-project.org/listinfo/interest

Reply via email to