Qt每天一例13.枚举转字符串
Posted 鱼酱2333
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt每天一例13.枚举转字符串相关的知识,希望对你有一定的参考价值。
Qt枚举转字符串
示例代码
#include<QMetaEnum>
class Demo:public QObject
Q_OBJECT
public:
enum EnmState
ENM_STATE_A = 0,
ENM_STATE_B = 2,
ENM_STATE_C,
ENM_STATE_D,
;
Q_ENUM(EnmState);
void show()
QMetaEnum enmState = QMetaEnum::fromType<Demo::EnmState>();
qDebug()<<enmState.name();//枚举的类型名称
qDebug()<<enmState.keyCount();//键个数
qDebug()<<enmState.isValid()<<enmState.scope();//是否有效 声明自哪个类
qDebug()<<enmState.keyToValue("ENM_STATE_A"); //字符串转枚举
qDebug()<<QString(enmState.valueToKey(ENM_STATE_A)); //枚举转字符串
qDebug()<<QString(enmState.valueToKey(ENM_STATE_B));
for(int i = 0;i < enmState.keyCount();i++) //遍历枚举
qDebug()<<QString(enmState.key(i))<<enmState.value(i);
;
EnmState
4
true Demo
0
“ENM_STATE_A”
“ENM_STATE_B”
“ENM_STATE_A” 0
“ENM_STATE_B” 2
“ENM_STATE_C” 3
“ENM_STATE_D” 4
- 模板类
class CEnmDef:public QObject
Q_OBJECT
public:
enum EnmDevSwitch
ENM_SWITCH_ON = 0,
ENM_SWITCH_OFF,
;
Q_ENUM(EnmDevSwitch)
template <typename EnmType>
static EnmType strToEnm(QString strText)
QMetaEnum metaEnm = QMetaEnum::fromType<EnmType>();
return (EnmType)metaEnm.keyToValue(strText.toStdString().data());
template <typename EnmType>
static QString enmToStr(EnmType enmVal)
QMetaEnum metaEnm = QMetaEnum::fromType<EnmType>();
return metaEnm.valueToKey(enmVal);
以上是关于Qt每天一例13.枚举转字符串的主要内容,如果未能解决你的问题,请参考以下文章