QML 枚举

QML 中使用的枚举可以在 QML 或 C++ 中定义。

有关在 QML 中定义枚举的信息,请参阅枚举属性(Enumeration Attributes)。

用 C++ 定义时,暴露给 QML 的枚举必须用Q_ENUMQ_ENUM_NS 宏标记,并且是通过QML_NAMED_ELEMENTQML_ELEMENT 宏暴露给 QML 的类型的一部分。更多详情,请参阅Enumeration Types(枚举类型)。

只有命名的 QML 类型才能容纳 QML 可用的枚举。每个枚举必须有一个围绕的命名类型。QML 命名空间也是 QML 类型,可以容纳枚举。

因此,枚举值可称为<Type>.<Value> 。例如,Text 类型有一个AlignRight 枚举值:

Text { horizontalAlignment: Text.AlignRight }

枚举值是由类型名产生的类型引用的属性。您也可以使用 JavaScript 的方括号语法检索它们,不过这种方法容易出错,不推荐使用:

// Avoid this if possible
Text { horizontalAlignment: Text["AlignRight"] }

在 QML 中使用枚举

在 QML 中,枚举不是独立的类型,而是其周围类型的属性。枚举值表示为枚举的底层类型。对于大多数枚举,使用 JavaScript 的Number类型或 QML 的double类型来存储它们是安全的。但是,这对于 64 位整数来说并不总是有效,因为它们的范围超出了 64 位双倍的安全整数范围。因此,安全整数范围(-(2^53 - 1) 至 2^53 - 1,包括在内)之外的枚举值无法在 QML 中安全使用。对于值在 32 位有符号整数数值范围内的枚举,可以安全地使用 QMLint类型作为存储空间。

例如

import QtQuick

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)
}

另请参阅 QML 值类型枚举属性枚举类型

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.