Search code examples
c++qtc++11enumsstrong-typing

QMetaEnum and strong typed enum


With plain enums I was able to access Q_ENUMS properties and specific, the character represenation of enums, with following code:

// in .h
class EnumClass : public QObject
{
  Q_OBJECT
public:
  enum  MyEnumType { TypeA, TypeB };
  Q_ENUMS(MyEnumType)
private:
  MyEnumType m_type;
};

// in .cpp
m_type = TypeA;
...
const QMetaObject &mo = EnumClass::staticMetaObject;
int index = mo.indexOfEnumerator("MyEnumType");
QMetaEnum metaEnum = mo.enumerator(index);
QString enumString = metaEnum.valueToKey(m_type); // contains "TypeA"

If I want to use the c++11 feature for strong typed enums like

enum class MyEnumType { TypeA, TypeB };

accessing the meta information does not work anymore. I guess, that Qt does not recognize it as an enum anymore.

Is there any solution to access the character represenation of an enum while using strong typed enums?


Solution

  • Q_ENUMS is obsolete, and Q_ENUM should be used instead, but the following code works for me with either of them (Qt 5.5, your issue might be caused by an old Qt version; also this question is relevant):

    .h:

    #include <QObject>
    class EnumClass : public QObject
    {
        Q_OBJECT
    public:
        enum class MyEnumType { TypeA, TypeB };
        EnumClass();
        Q_ENUM(MyEnumType)
    private:
        MyEnumType m_type;
    };
    

    .cpp:

    #include <QDebug>
    #include <QMetaEnum>
    #include <QMetaObject>
    EnumClass::EnumClass()
    {
        m_type = MyEnumType::TypeA;
        const QMetaObject &mo = EnumClass::staticMetaObject;
        int index = mo.indexOfEnumerator("MyEnumType");
        QMetaEnum metaEnum = mo.enumerator(index);
        // note the explicit cast:
        QString enumString = metaEnum.valueToKey(static_cast<int>(m_type));
        qDebug() << enumString;
    }
    

    main:

    int main()
    {
        EnumClass asd;
        return 0;
    }
    

    output:

    "TypeA"