QMetaEnum and strong typed enumeration

With equal enumerations, I was able to access the Q_ENUMS properties and the concrete representation of character enumerations with the 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 function for strong typed enums, for example

enum class MyEnumType { TypeA, TypeB };

access to metadata no longer works. I believe Qt will no longer recognize it as an enumeration.

Is there any solution for accessing a character enumeration representation of characters when using strong typed enums?

+4
source share
1 answer

Q_ENUMS , Q_ENUM, (Qt 5.5, Qt, ):

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

:

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

:

"TypeA"

+1

Source: https://habr.com/ru/post/1612250/


All Articles