
枚舉類型
class Enum : public QObject{
Q_OBJECT
public:
enum Fruit{
APPLE = 0,
BANANA,
POTATO
}
Q_ENUM(Fruit);//向Qt注冊此枚舉文件,若有多個枚舉,則在對應枚舉下注冊即可,如下
enum Vagetables{
TOMATO,//默認初值從零起
ONION,
POTATO
}
Q_ENUM(Vagetables);//嗯
}
值轉枚舉 int to Enum
int fruitType = 0;
Enum::Fruit fruit = (Enum::Fruit)fruitType;//Enum本身還是數值型的,所以只需要直接強制類型轉換即可。但是我沒有試過枚舉不存在的值強制轉換成枚舉會是什么
值轉枚舉項的字符(Value to key) int to QString
#include <QMetaEnum>
int fruitType = 0;
QMetaEnum meta = QMetaEnum::fromType<Enum::Fruit>();
QString itemKey = meta.valueToKey(fruitType);
字符串轉枚舉值,結果為數字(Key to Value) QString to Enum
QString fruit = "POTATO";
QMetaEnum meta = QMetaEnum::fromType<Enum::Fruit>();
int value = meta.keyToValue(fruit.toStdString().data());//入參是char *
字符串轉枚舉類型,結果為枚舉,QString to Enum
QString fruit = "POTATO";
QMetaEnum meta = QMetaEnum::fromType<Enum::Fruit>();
Enum::Fruit fruitItem = (Enum::Fruit)meta.keyToValue(fruit.toStdString().data());//入參是char *
枚舉轉字符串,Enum to QString
Enum::Fruit fruit = Fruit::POTATO;
QMetaEnum meta = QMetaEnum::fromType<Enum::Fruit>();
QString fruitStr = meta.valueToKey(fruit);