Is there a way to use QMetaEnum with Q_ENUMS belonging to non Q_OBJECT or Q_GADGET class?

No, there isn't, because Q_ENUM's functionality is implemented in code generated by moc, and moc ignores classes that are neither Q_OBJECT nor Q_GADGET. There's no reason for not using a Q_GADGET since it has no effect on object size: adds no virtual methods nor data fields.

The following demonstrates this:

#include <QtCore>

namespace Ns {
class Class {
   Q_GADGET
public:
   enum ESomeEnum {ENUM_A, ENUM_B, ENUM_C};
   Q_ENUM(ESomeEnum)
};
}

int main() {
   auto metaEnum = QMetaEnum::fromType<Ns::Class::ESomeEnum>();
   qDebug() << sizeof(Ns::Class) << metaEnum.valueToKey(Ns::Class::ENUM_A);
}
#include "main.moc"

Output:

1 ENUM_A

On this particular platform (and many others), empty classes are of size 1.


Q_ENUM is like the old Q_ENUMS but with these differences:

  • It needs to be placed after the enum in the source code.
  • Only one enum can be put in the macro.
  • It enables QMetaEnum::fromType<T>().
  • These enums are automatically declared as a QMetaTypes (no need to add them in Q_DECLARE_METATYPE anymore).
  • enums passed to qDebug will print the name of the value rather than the number.
  • When put in a QVariant, toString() gives the value name. The value name is printed by QCOMPARE (since Qt 5.6)

Taken from WOBOQ blog post on the topic, read it for additional information regarding Q_ENUM vs Q_ENUMS.


Yes, since 5.8 you can do:

namespace MyLibrary
{ 
Q_NAMESPACE 

enum class MYLIBRARYSHARED_EXPORT MyEnumClass
{
...
}; 

Q_ENUM_NS(MyEnumClass)

...
} // namespace MyLibrary