Unable to declare Q_ENUM from an enumeration defined in another class

This documentation states

If you want to register an enumeration declared in another class, the enumeration must be fully qualified with the name of the class that defines it. In addition, the class that defines the enumeration must inherit a QObject, and also declare the enumeration using Q_ENUMS ().

However, I cannot do this work in the following example.

Grade A:

#ifndef CLASSA_H #define CLASSA_H #include <classb.h> class ClassA : public QObject { Q_OBJECT Q_ENUMS(ClassB::TestEnum) public: explicit ClassA(QObject *parent = 0) : QObject(parent) { const QMetaObject *metaObj = this->metaObject(); qDebug() << metaObj->enumeratorCount(); } }; #endif // CLASSA_H 

ClassB:

 #ifndef CLASSB_H #define CLASSB_H #include <QDebug> #include <QMetaEnum> #include <QObject> class ClassB : public QObject { Q_OBJECT Q_ENUMS(TestEnum) public: enum TestEnum { A, B, C }; explicit ClassB(QObject *parent = 0) : QObject(parent) { const QMetaObject *metaObj = this->metaObject(); qDebug() << metaObj->enumeratorCount(); } }; #endif // CLASSB_H 

home:

 #include <classa.h> #include <classb.h> int main() { ClassA objectA; ClassB objectB; } 

Expected Result:

1

1

Actual output:

0

1

+6
source share
1 answer

Here is a summary of a little research:

  • The information provided in the documentation on registering an enumeration declared in another class seems outdated.

  • Q_ENUMS(Class::EnumName does not create a new counter and is useless.

  • When you declare a new Q_PROPERTY in ClassA, you should use the full enumeration form ClassB::EnumName .

  • Once EnumName registered with ClassB, it no longer needs to be registered.

  • A property created using an enumerator from another class is working correctly.

     class ClassA : public QObject { public: Q_OBJECT Q_PROPERTY(ClassB::TestEnum test READ test) public: explicit ClassA(QObject *parent = 0) { const QMetaObject *metaObj = this->metaObject(); qDebug() << metaObj->enumeratorCount(); QMetaProperty property = metaObj->property(metaObj->indexOfProperty("test")); if (property.isEnumType()) { const QMetaEnum& enumerator = property.enumerator(); qDebug() << enumerator.name(); for (int i = 0 ; i < enumerator.keyCount(); i++) { qDebug() << QLatin1String(enumerator.key(i)) << enumerator.value(i); } } } ClassB::TestEnum test() const { return ClassB::A; } }; 

Output:

 0 TestEnum "A" 0 "B" 1 "C" 2 
+5
source

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


All Articles