[Development] Enumerations in QML

Erik Verbruggen erik.verbruggen at me.com
Thu Dec 13 11:09:44 CET 2012

Replying to myself after a bit of pondering...

On Dec 12, 2012, at 10:45, Verbruggen Erik <Erik.Verbruggen at digia.com> wrote:

> The problem with enums is that we couldn't make them fast. They will always be a lot slower than normal string literals. That is mostly because we could not avoid the name lookup. Think about,
>   Text {
>           alignment: Alignment.Vertical | Alignment.something
>    }
> there is no way for you to remove the name lookups for "Alignment", "Vertical", and "something". Also, there is no way for you to distinguish "Types" (e.g. Item, Rectangle, and co...) from "Enums" (in our case "Alignment"). That means, you cannot build the correct list of dependencies when loading a QML Component.

I didn't think this fully through yet, but it looks that it might work..:

What we could do is to elevate QML enums to (nearly) QML type status. The drawback is that an enum has to be in its own file, but it solves the dependency problem. It also does not allow for "inline" or "local" enums. An example:

  enum Alignment { // or possibly only "enum {", although I think readability suffers
    vertical // automatically assigned string is "vertical"
    horizontal: "horizontal"

We could use the static nature of QML objects (and then also enums) to have an engine do lookups once when loading. Going a bit further, when an enumerator is used, I think we could replace the enumerators with their string representation. That would also make them compatible with existing properties that expect strings.

About the scoping: inserting the enumerators into the parent scope (à la C/C++) will give a (big) performance penalty. It would mean that all files in a package need to be loaded (or at least peeked at) just to find out if they define an enum. 

The question is if the above adds any value over something you can already do:

  QtObject {
    property string vertical: "vertical"
    property string horizontal: "horizontal"

-- Erik.

More information about the Development mailing list