QMetaEnum does not read keys from enum

Viewed 83

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.

Header file with the enum:

#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
    }

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 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.

1 Answers

You're missing an important thing:

class Planet: public QObject
{
    Q_OBJECT

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

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

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.

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

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

Related