Search code examples
c++enumsqt4

How to use enum in Qt?


I have a QObject class Message and another one named Request that inherits the message class. Here's the header file:

#ifndef MESSAGE_H
#define MESSAGE_H

#include <QObject>

class Message : public QObject
{
    Q_OBJECT
public:
    explicit Message(QObject *parent = 0);
    QString Source;
    QString Destination;
    QString Transaction;
    QList<QObject> Content;
signals:

public slots:

};

class Request : public Message
{
    Q_OBJECT
    Q_ENUMS(RequestTypes)
public:
    explicit Request();
    enum RequestTypes
      {
         SetData,
         GetData
      };

    RequestTypes Type;
    QString Id;
};

#endif // MESSAGE_H

Now I want to create a Request in my code and set Type to SetData. How can I do that? Here's my current code which gives the error "'Request::RequestTypes' is not a class or namespace". The header file from above is included in my main programs header file, so Request is known and can be created and I can set the other properties - but not the Type:

Request *r = new Request();
r->Source = "My Source";
r->Destination = "My Destination";
r->Type = Request::RequestTypes::SetData;

In other words: I could as well had taken a QString for the Type property of a Request, but it would be nice and safer to do this with an enum. Can someone please show me what's wrong here?


Solution

  • You need to declare the enum like so:

    enum class RequestTypes
      {
         SetData,
         GetData
      };
    

    in order to use it like you did, but that requires C++11.

    The normal usage would be (in your case): r->Type = RequestTypes::SetData;