Q_ENUM(enum_name) works with only enums declared inside class. srsly?



  • Let's look at example from documentation which is copied next.

    class Message : public QObject
     {
         Q_OBJECT
         Q_ENUMS(Status)
         Q_PROPERTY(Status status READ status NOTIFY statusChanged)
     public:
         enum Status {
             Ready,
             Loading,
             Error
         };
         Status status() const;
     signals:
         void statusChanged();
     };
    

    In this example we declare our enumeration declared inside class with Q_ENUM(). It is ok. But what if we want to use Globally declared enumeration. Qt gives errors. How can we achieve operating with enumerations declared outside the class?


  • Lifetime Qt Champion

    Hi,

    You can't, Q_ENUMS need a meta object provided either by the QObject class or the Q_GADGET macro



  • This is an old topic, but still comes up as one of the first Google results. I just wanted to add:

    If the main goal is to use the enum as a property, it is sufficient to just use Q_DECLARE_METATYPE after the globally-declared enumeration.

    If you need the other conveniences of Q_ENUM, then SGaist's reply applies.


  • Moderators

    @Kofr said in Q_ENUM(enum_name) works with only enums declared inside class. srsly?:

    How can we achieve operating with enumerations declared outside the class?

    This is possible since Qt 5.8 where the Q_NAMESPACE macro was introduced. This enables the generation of a MOC object also for namespaces.

    namespace MyNamespace
    {
        Q_NAMESPACE
     
        enum MyEnum {
            Foo,
            Bar
        };
        Q_ENUM_NS(MyEnum)
    }
    

    Note the Q_ENUM_NS macro here. There is also a Q_FLAG_NS macro available.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.