QMetaEnum 不从枚举中读取键 [英] QMetaEnum does not read keys from enum

查看:54
本文介绍了QMetaEnum 不从枚举中读取键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的代码没有从我的枚举中读取我指定的键.

why my code does not read my specified keys from my enum.

代码本身编译良好,程序运行时没有任何运行时错误.

The code itself compiles fine and the program runs without any runtime errors.

带有枚举的头文件:

#include <QMetaEnum>

    class Planet: public QObject
    {

    public:    
        enum PlanetTypes
        {
            Barren,Gas,Ice,Lava,Oceanic,Plasma,Storm,Temperate
        };Q_ENUM(PlanetTypes)
        Planet();
        //some getters and setters for my private membervariables
    }

这是我使用 QMetaEnum 读取枚举的数据模型中的方法

And here is the method from datamodel where I read the enum using QMetaEnum

    QStringList DataModel::getPlanetTypes()
    {
        QStringList PlanetTypesList;

        Planet p;
        const QMetaObject* metaObj = p.metaObject();
        QMetaEnum e = metaObj->enumerator(metaObj->indexOfEnumerator("PlanetTypes"));
        for(int i=0; i<e.keyCount();i++)
        {
            PlanetTypesList.append(e.key(i));
        }
        return PlanetTypesList;

    }

Debug 显示 QMetaEnum e 没有找到 Enumerator.for 循环从不运行.

Debug shows that the QMetaEnum e does not find the Enumerator. The for loop never runs.

但是没有编译器或运行时错误.

But there is no compiler - or runtime error.

我实际上不知道为什么它找不到枚举或其键.

I have actually no clue why it does not find the enum or its keys.

推荐答案

你错过了一个重要的事情:

You're missing an important thing:

class Planet: public QObject
{
    Q_OBJECT

并且应该有非空的类 vtable,例如至少

and should have non-empty vtable for class, e.g. at least

    ~Planet();  // can be empty but should not be inlined
 }

如果没有 Q_OBJECT 或 Q_GADGET 宏,元对象编译器 (MOC) 实用程序根本不会扫描您的类.因此,由它生成的代码将不包含会形成和初始化您想要存在的 QMetaEnum 实例的代码.实际上,如果没有那个宏,就不会声明特定于 Planet 的元对象,它将继承 QObject 的元对象.

Without Q_OBJECT or Q_GADGET macro the meta-object compiler (MOC) utility won't scan your class at all. So code generated by it will not contain code that would form and initialize instance of QMetaEnum you want to exist. Actually without that macro there will be no Planet-specific meta object declared and it will inherit QObject's one.

确保在添加后重新运行 qmake,否则可能会遇到链接错误.

Make sure that you would re-run qmake after adding this or you may encounter linking errors.

顺便说一句,如果您不需要该类的实例,您可以使用 Planet::staticMetaObject 代替.

Btw, you can use Planet::staticMetaObject instead if you don't need an instance of that class.

这篇关于QMetaEnum 不从枚举中读取键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆