PDA

View Full Version : Using QMetaEnum



lxman
13th March 2011, 23:18
Right now I have a header file called enums.h as such:

enums.h

#ifndef ENUMS_H
#define ENUMS_H

#include <Qt>

enum paper_orient{portrait, landscape};
enum ruler_orient{top_ruler, bottom_ruler, left_ruler, right_ruler};
enum relationships_type{line_item, other};
enum settings_type{line_object, plot, text};

#endif // ENUMS_H


With this setup, wherever I want to use these enums, I just #include "enums.h" and they are available.

In learning to do things the Qt way, it appears that QMetaEnum would be a more streamlined approach.

In the docs, I find this example:

class MyClass : public QObject
{
Q_OBJECT
Q_ENUMS(Priority)

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

enum Priority { High, Low, VeryHigh, VeryLow };
void setPriority(Priority priority);
Priority priority() const;
};

If I use this approach, does this mean that the Priority enum is only available within MyClass? What if I wish to use this enum in other classes? Ultimately that is what I would like to establish, is a series of global enums that are available anywhere in my project.

squidge
13th March 2011, 23:29
If I use this approach, does this mean that the Priority enum is only available within MyClass? What if I wish to use this enum in other classes? Ultimately that is what I would like to establish, is a series of global enums that are available anywhere in my project.

Yes, and you simply qualify it by class name, eg: MyClass::Priority priority

lxman
14th March 2011, 00:01
Okay, experimenting a bit with this concept, here is what I see:

With my current system, when I want to use my enums, I do #include "enums.h" and then when I want to, for instance, declare a variable of type settings_type, I do the following:

#include "enums.h"
.
.
.
settings_type vara;
vara = plot;
Now if I declare a class, MyEnums, in order to use the enums, I now do this:

#include "myenums.h"
.
.
.
MyEnums::settings_type vara;
vara = MyEnums::plot;
This has just increased the amount of my code.

So, could somebody explain to me what other advantages there might be to using QMetaEnum that make up for the increased complexity?

squidge
14th March 2011, 08:11
Firstly I wouldn't create a class called MyEnums, instead each enum would be relevent to the class they belong to; meaning I can use the same enum value in numerous classes witout worrying about ambiguation between them.

Secondly, it allows you to easily serialize and deserialize enumerations. At Qt Developer Days 2007, this was described in some detail. If you did not attend, you can download the slides from here: ftp://ftp.qt.nokia.com/videos/DevDays2007/DevDays2007%20-%20Secrets_of_Qt.pdf