C

enumeration QML Basic Type

a named enumeration value. More...

The enumeration type refers to a named enumeration value.

Each named value can be referred to as <Type>.<value>. For example, the Text type has an AlignRight enumeration value:

Text { horizontalAlignment: Text.AlignRight }

When integrating with C++, note that any enum value passed into QML from C++ is automatically converted into an enumeration value, and vice-versa.

This basic type is provided by the QML language. Some enumeration values are provided by the QtQuick import.

Using the enumeration Type in QML

The enumeration type is a representation of a C++ enum type. It is possible to refer to the enumeration type in QML itself; but instead, the int type shall be used when referring to enumeration values from QML code.

For example:

import QtQuick 2.15

Item {
    // refer to Text.AlignRight using an int type
    property int enumValue: textItem.horizontalAlignment

    signal valueEmitted(int someValue)

    Text {
        id: textItem
        horizontalAlignment: Text.AlignRight
    }

    // emit valueEmitted() signal, which expects an int, with Text.AlignRight
    Component.onCompleted: valueEmitted(Text.AlignRight)
}

Defining enumerations with the same enumerators

In some cases you want to have many enumerations that have the same enumerators:

Item {
    enum DeviceUnits {
        Unknown,
        Metric,
        Imperial
    }

    enum AppUnits {
        Unknown,
        Metric,
        Imperial
    }
}

The way of using the same enumerators illustrated above is not supported in Qt Quick Ultralite, but there are options on how to achieve the same result.

  • Use a sensible prefix for your enumerators:
    Item {
        enum DeviceUnits {
            D_Unknown,
            D_Metric,
            D_Imperial
        }
    
        enum AppUnits {
            A_Unknown,
            A_Metric,
            A_Imperial
        }
    }
  • If you use your enumerations in the same qml file only, wrap them in a named inline component:
    Item {
        component D : QtObject {
            enum DeviceUnits {
                Unknown,
                Metric,
                Imperial
            }
        }
    
        component A : QtObject {
            enum AppUnits {
                Unknown,
                Metric,
                Imperial
            }
        }
    }
  • Or create a separate qml file for each enumerator:
    // DeviceUnits.qml
    QtObject {
        enum DeviceUnits {
            Unknown,
            Metric,
            Imperial
        }
    }
    // AppUnits.qml
    QtObject {
        enum AppUnits {
            Unknown,
            Metric,
            Imperial
        }
    }

See also QML Basic Types, enum type as a property type, and QML Object - Enumeration Attributes.

Available under certain Qt licenses.
Find out more.