Solved qmlregistersingletoninstance
-
I am trying to find information regarding qmlRegisterSingletonInstance(), but found almost none. The best one I found is here
https://code.woboq.org/qt5/qtdeclarative/src/qml/doc/src/qmlfunctions.qdoc.htmlI wondering what is the difference between qmlRegisterSingletonInstance() and instantiate an instance and register it with QQmlContext::setContextProperty(const QString &name, QObject *value) ?
It seem that I can access to the c++ instance the same way in QML with these 2 different method. Can some one elaborate more on qmlRegisterSingletonInstance()?Thanks
-
@TonyN
Basically we do singleton instance when :
We want to use a single object of a class throughout the lifetime of an application.Check the link below:
https://doc.qt.io/qt-5/qtqml-cppintegration-overview.html -
Lookup of context properties is more expensive than singleton (it has to traverse the context hierarchy all the way to the root context to find a context property) and less typed (singleton needs an import statement and the engine know the type thanks to the registration). Qt Creator also will also have an easier time providing auto complexion on it.
In QML 3 context properties will be removed.
So for new code use
qmlRegisterSingletonInstance()
and avoidQQmlContext::setContextProperty()
. -
@GrecKo Thank you. That explains it.