-->

Qt: No metadata by meta.enumeratorCount() for enum

2020-04-19 06:00发布

问题:

I have the following class, where I try to obtain some metadata of an enum MyEnum. However, when looping over meta.enumeratorCount() its count is always 0. Basically I was follwing this example here. In order to find the problem, I was trying the same with methods too, same problem - method count 0. Code compiles, no errors no warnings.

Must be a silly mistake .... maybe you can help me

class FsxSimConnectQtfier : public QObject
{
    Q_OBJECT
public:
    explicit FsxSimConnectQtfier(QObject *parent = 0);
    enum MyEnum { G1, G2 };
    static const QString simConnectExceptionToString(const DWORD id);
};

const QString FsxSimConnectQtfier::simConnectExceptionToString(const DWORD id) {
    // int i= FsxSimConnectQtfier::staticMetaObject.indexOfEnumerator("MyEnum");
    // -1 -> not found, why?
    QMetaObject meta = FsxSimConnectQtfier::staticMetaObject;
    for (int i=0; i < meta.enumeratorCount(); ++i) {
        QMetaEnum m = meta.enumerator(i); // never reached, why?
    }
    return "";
}

回答1:

You need to register the enum with the metadata system using the Q_ENUMS() macro:

class FsxSimConnectQtfier : public QObject
{
    Q_OBJECT
    Q_ENUMS(MyEnum)  // <--- 

public:
    explicit FsxSimConnectQtfier(QObject *parent = 0);
    enum MyEnum { G1, G2 };
    static const QString simConnectExceptionToString(const unsigned int id);
};


标签: c++ qt qt4 qobject