反射实例
最后更新于:2022-04-02 02:14:18
[TOC]
## 反射实例
```
// 注册属性
Q_PROPERTY(CustomType type READ getType WRITE setType NOTIFY valueChanged)
// 添加枚举
enum CustomType{
Corporate,Individual,Educational,Goverment
};
Q_ENUMS(CustomType);
// 反射
void setType(QString newType){
// 使用 static 只需要初始化一次
static const QMetaObject* meta = metaObject();
static int propindex = meta->indexOfProperty("type");
static const QMetaProperty mp = meta->property(propindex);
QMetaEnum menum = mp.enumerator();
const char* ntype = newType.toAscii().data();
CustomType theType =static_cast(menum.keyToValue(ntype));;
if(theType!=m_type){
CustomType oldType =m_type;
m_type=theType;
emit valueChanged("type",theType,oldType)
}
}
```
使用反射获取传参的字符串对应的枚举值
';