Qt在5.5开始,支持在C++中定义一个枚举。
采用Q_ENUM关键字,注册自定义的枚举到元对象系统中,供QML使用。
这,说实话,非常麻烦,非常麻烦,非常麻烦
嗯,麻烦的事情要说3次。
以至于长期以来,在不想涉及太多C++的情况下,我自己开发QML程序都是用字符串做枚举,比如说“XxxStyle”
这个问题,终于在5.10解决了。5.10中允许在QML中自定义枚举值,方式如下:
MyRectangle.qml
import QtQuick 2.10
Rectangle {
id: myRectangle
width: 100
height: 100
color: {
switch ( currentStyle )
{
case MyRectangle.Style.RedStyle: return "#ff0000";
case MyRectangle.Style.GreenStyle: return "#00ff00";
case MyRectangle.Style.BlueStyle: return "#0000ff";
default: return "#00000000";
}
}
enum Style {
RedStyle,
GreenStyle,
BlueStyle
}
property int currentStyle: MyRectangle.Style.RedStyle
}
这里我自定义了一个枚举,名字是Style,里面有3个属性,分别是RedStyle、GreenStyle和BlueStyle
同时有个currentStyle来接收枚举值
使用的话,要遵守QML文件名.枚举类型名.枚举值名
的规则来使用,无论是在当前QML内还是外部。
最后这个MyRectangle可以这样使用:
MyRectangle {
currentStyle: MyRectangle.Style.GreenStyle
}
总体来说,比以前C++注册,然后在QML使用的方法,方便了很多很多。但是!!我必须要吐槽一点,5.10自带的QtCreator竟然不能正确识别enum关键字,导致整个QML文件内都无法正常高亮。只能等后面版本能够改进了。