QMetaEnum and strong typed enum
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"