[Development] QML Singletons

Alan Alpert 416365416c at gmail.com
Tue Dec 11 17:22:38 CET 2012


On Tue, Dec 11, 2012 at 1:52 AM, Thomas Hartmann
<Thomas.Hartmann at digia.com> wrote:
> Am 11/12/2012 10:23, schrieb Knoll Lars:
>
> Hi,
>
>
>>>> it's a bit weird that you need a qmldir for that. Wouldn't it be better if we could mark this as singleton in the implementation (ie. inside single.qml)? Maybe use a new keyword for that? static is already a reserved keyword in Ecmascript 5.1, so we could maybe write single.qml as:
>>>>
>>>> static QtObject {
>>>>     property int myproperty;
>>>>     ...
>>>> }

It's more of a file level distinction, but that could work. So when a
QML file has the static keyword on its root object, it is loaded as a
singleton type? And the static keyword is invalid when not on a root
object?

Keep in mind that this should be valid, even though it's a tree with
four objects:
static QtObject {
    property int myProperty
    property MyItem subItem: MySubItem { MySubSubItem{}, MySubSubItem{}}
}

>>>
>>>
>>> But how would the engine know about single.qml being static? AFAIK all
>>> .qml parsing is done on demand. The engine would have to know that
>>> single.qml is a singleton from another source (Or scan all .qml files
>>> upfront for the static keyword).
>>
>> Sure, but it won't matter until you reference Single somewhere. The singleton should not get loaded before that anyway. And once you have a reference to it, the QML engine will try to load the file and then figure out it's static. That would require some work in the engine, but I think it might be doable.
>>
>
> Ah. I thought the singletons would still be referenced by one global id.
>
> If the singleton is accessed by an object definition then the question
> is what exactly is allowed.
> All properties would probably have to be read only for example, or we
> would depend on the order of instantiation.
>
> MySingleton {
>     id: myLocalAccessId
> }
>
> MyItem {
>     localProperty: myLocalAcessId.property
> }
>
>
> Not sure if just using an id would not be simpler:
>
>
> MyItem {
>     localProperty: mySingleton.property
> }

Actually the way to *use* singletons in QML is already defined,
because you can declare a C++ type as a singleton (
http://qt-project.org/doc/qt-5.0/qtqml/qqmlengine.html#qmlRegisterSingletonType
).

So using the singleton will look like this

MyItem {
    localProperty: MySingleton.property
}

Attempting to create an instance of the type, even like MySingleton {
id: mySingleton }, would result in an error.

--
Alan Alpert



More information about the Development mailing list