How can we declare enumerations in QML, without any JavaScript?

user4569486 picture user4569486 · Dec 25, 2015 · Viewed 16.5k times · Source

Does QML allow us to define enums? If so, how we can declare enumerations in QML?

I want to declare an enum in QML like the following C++ enum. If possible, I want to do this without any JavaScript.

enum Color { RED, GREEN, BLUE };
Color r = RED;
switch(r)
{
    case RED  : std::cout << "red\n";   break;
    case GREEN: std::cout << "green\n"; break;
    case BLUE : std::cout << "blue\n";  break;
}

What should I do?

Answer

Paul Masri-Stone picture Paul Masri-Stone · May 4, 2018

Since Qt 5.10, enumerations are directly supported in QML. See Qt documentation which contains sample code.

You can define one with the enum keyword. The type and its values must start with a capital letter but otherwise follow rules for naming a variable (e.g. can include digits and underscore).

To use the enum, you have to explicitly include the full scope including the component ComponentName.EnumType.EnumValue. This is true even when using it within the component itself.

e.g.

// MyComponent.qml
Rectangle {
    id: root

    // Define Shape enum
    enum Shape {
        None,
        Round,
        Pointy,
        Bobbly,
        Elusive
    }

    // Note: property using enum is of type int
    property int selectedShape: MyComponent.Shape.None

    visible: selectedShape !== MyComponent.Shape.None
    color: selectedShape === MyComponent.Shape.Pointy? "red": "green"
}

Note that enumerated values are treated as int and you can assign and compare them as such.

Although not documented (and therefore potentially subject to change), by default the first one has value 0, the second 1, etc.. However you can assign a non-negative integer value. You can even assign two enum values to the same integer value though that is probably not a good idea. You cannot assign an expression that evaluates to an integer.

e.g.

enum Shape {
    None = 5, // valid
    Round, // automatically assigned 6
    Pointy = -1, // not valid
    Bobbly = Round // not valid
    Elusive = (8-7) // not valid
}

Thanks to Michael Brasser's blog comment about assigning simple values.