Qt元对象学习之Qt中的反射机制之Q_PROPERTY

昨天在微信公众号上看到小豆君分享了一个篇文章名为:《Qt中的反射机制之Q_PROPERTY》看完之后自己研究了一下,现在记录一下心得

mystudent.h

mystudent.cpp

main.cpp

由于该代码在复制粘贴时候出现格式错乱,于是就贴图了,上面是小豆君原版代码,我改过之后的代码会在下面给出链接。

下面是我给setSex(const QString &sex)加了一些我的理解

void MyStudent::setSex(const QString &sex)
{
    //首先获取元对象指针
    static const QMetaObject *meta = metaObject();

    //Returns the number of properties in this class, including the number of properties provided by each base class
    //获取该类所有的属性值
    QStringList properties;
    for(int i = meta->propertyOffset(); i < meta->propertyCount(); ++i)
        properties << QString::fromLatin1(meta->property(i).name());

    qDebug()<<properties;
    //这里输出结果:("id", "name", "sex")


    //根据属性名Sex查找m_sex属性对象QMetaProperty
    //发现属性名并返回其索引;否则返回-1。根据属性名"sex"查找该属性的索引
    static int propindex = meta->indexOfProperty("sex");


    //Returns the meta-data for the property with the given index. If no such property exists, a null QMetaProperty is returned.
    //返回与给定属性的元数据索引。如果没有这样的属性存在,返回一个null QMetaProperty。
    static const QMetaProperty mp = meta->property(propindex);

    //Returns the enumerator if this property's type is an enumerator type; otherwise the returned value is undefined.
    //返回枚举器如果这个属性的类型是一个枚举器类型;否则返回的值是未定义的。
    QMetaEnum menum = mp.enumerator();

    //把传入的sex转换成const char *
    const char *ntyp = sex.toStdString().c_str();

    //Returns the integer value of the given enumeration key, or -1 if key is not defined.
    //返回给定的枚举的整数值键,或-1如果没有定义的关键。
    m_sex = static_cast<Sex>(menum.keyToValue(ntyp));
    qDebug()<<"QMetaEnum"<<m_sex<<menum.name()<<menum.key(m_sex)<<menum.valueToKey(Sex::Man);

}

接下来修改了getSex函数,使其可以返回枚举类型的字符串而不是下标

QString MyStudent::getSexString() const
{
#if 0
    //这种方式只返回m_sex的数字下标
    return property("sex").toString();
#else

    QMetaEnum metaEnum = QMetaEnum::fromType<MyStudent::Sex>();
    QString str = metaEnum.valueToKey(m_sex);
    return str;

#endif
}

具体代码:https://download.csdn.net/download/lsyrhz/11165804

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liu-Eleven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值