1

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

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.

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42
  • The thing is, when i add Q_OBJECT to this class i get then the issue i have mentioned here: https://stackoverflow.com/questions/67934821/converting-enum-into-string-using-qmetaenum – Rolf Hausen Jun 12 '21 at 15:04
  • @RolfHausen no,, removing macro isn't a solution. You have to have a destructor defined, make sure it's not an inlined destructor (~QObject is virtual, but newer versions f GCC have bad habit to optimize it out if derived object wasn't used as virtual) , make sure that moc was re-run after that. If GCC remove last virtual function from your class or you have no virtual function defined, it fails. – Swift - Friday Pie Jun 12 '21 at 16:12
  • @swift-friday-pie Thank you very much! this was the solution. I would not have found this easily by my self. – Rolf Hausen Jun 13 '21 at 12:33