[Development] QML Singletons

Alan Alpert 416365416c at gmail.com
Tue Dec 11 04:55:19 CET 2012


Qt 5 gains this great new qmlRegisterSingletonApi function for
exposing global functionality from C++. This is great but sometimes
you want to write that global functionality in QML instead of C++. Use
cases that come to mind include UI constants and a fake business logic
backend when prototyping. How to expose this to QML is the real
challenge, the details of how it works is pretty straight forward -
the specified QML file acts as a factory and then it's the exact same
as qmlRegisterSingleonApi.

My current concept for this feature is to add another keyword to
qmldir. Like internal, you could mark a type as as singleton. So a
qmldir could look like:

module Qt.labs.example
Test 1.0 Test.qml
Test 1.1 Test1.qml
internal InternalType 1.1 Internal.qml
singleton Single 1.1 single.qml

So when you import that module the Single type is a singleton and you
can access methods and properties of the instance (which is just an
instance of the object tree defined in single.qml). Note for the
prototyping case this does mean you need a qmldir file, but those
still work with relative paths so it can be as simple as import ".".

Keep in mind this feature may require language changes so I've no idea
when it would actually land in Qt. But it'll never get in until there
is agreement on how the feature should look.

--
Alan Alpert



More information about the Development mailing list