c++qtenumerationqgadget

Unable to iterate over a Qt enumeration


I am trying to iterate over an enumeration.

    class MyEnumClass : public QObject
    {
        Q_GADGET
        Q_ENUMS(MyEnum)

    public:
        enum MyEnum
        {
            a, b, c
        };

        MyEnumClass(QObject *parent = 0){}
    };

    void listAllItems()
    {    
        QMetaObject meta = MyEnumClass::staticMetaObject;
        int count =  meta.enumeratorCount();
        for (int i=0; i < count; ++i)
        {
           QMetaEnum m = meta.enumerator(i);
           QString x;
           MyEnumClass::MyEnum y;
           x = m.valueToKey(i);
           y = (MyEnumClass::MyEnum)m.value(i);
        }
    }    

As I step through the loop I should be able to see my enumeration, with name in x and value in y.

Unfortunately I am able to only see the first value, count is always 1.

I looked at this question to figure out the code above - but I did reqister my enum, my problem should be a different one. Qt: No metadata by meta.enumeratorCount() for enum in Q_OBJECT, why?

What am I missing ?


Solution

  • Looks to me like meta.enumeratorCount() will return the number of registered enums. In your case, you have only one. You want to get the QMetaEnum corresponding to MyEnum by calling meta.enumerator(0). You can then use QMetaEnum::keyCount and QMetaEnum::key to list the keys in the enum.