[Interest] QML Singleton and QTimer?

Ulf Hermann ulf.hermann at qt.io
Mon May 10 09:08:19 CEST 2021


> 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.


More information about the Interest mailing list