20

I just found multiple examples showing the usage of Q_ENUM and Q_ENUMS and looking into the definition of Q_ENUM showed me that it includes Q_ENUMS and other definitions.

I am not sure which one to write when using the enum in Q_PROPERTY, Qml/QtQuick, in signals/slots, QVariants and qDebug() output.

It seems like the Q_ENUM is the better one as it is defined using Q_ENUMS, but I'm just guessing here.

What exactly are the differences, why are there two at all and which one should be prefered?

feedc0de
  • 3,646
  • 8
  • 30
  • 55

2 Answers2

16

The What's New in Qt 5.5 says:

Added Q_ENUM to replace Q_ENUMS, which allows to get a QMetaEnum at compile time using QMetaEnum::fromType. Such enums are now automatically registered as metatypes, and can be converted to strings within QVariant, or printed as string by qDebug().

Andrii
  • 1,788
  • 11
  • 20
8

Since Qt 5.5 Q_ENUMS is deprecated, replaced with the better Q_ENUM.

There is an example showing its use in the Qt documentation:

class MyClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged)

public:
    MyClass(QObject *parent = 0);
    ~MyClass();

    enum Priority { High, Low, VeryHigh, VeryLow };
    Q_ENUM(Priority)

    void setPriority(Priority priority)
    {
        m_priority = priority;
        emit priorityChanged(priority);
    }

    Priority priority() const
    { 
        return m_priority; 
    }

signals:
    void priorityChanged(Priority);

private:
    Priority m_priority;
};

For further details on the reasons behind the move from Q_ENUMS to Q_ENUM, read this blog entry

Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213
  • Is the example supposed to illustrate a difference between `Q_ENUM` and `Q_ENUMS` or simply how `Q_ENUM` can be used? – HelloGoodbye Nov 27 '17 at 17:00
  • @HelloGoodbye The example illustrates how to use `Q_ENUM`. `Q_ENUMS` has been deprecated, and should no longer be used. – Steve Lorimer Nov 27 '17 at 17:01
  • The question was explicitly "what is the difference". Everyone knows that deprecated stuff shouldn’t be used anymore, so showing what wasn’t possible before, or what pitfall are avoided with the new method is a much better way to answer such question. – Robin Jun 07 '21 at 08:56
  • @Robin if you read the question it is clear OP didn't know it was deprecated, and was asking which to use and why. Stating one is deprecated should be sufficient to signal "don't use this one, use the other". – Steve Lorimer Jun 07 '21 at 09:05