Convert Enum to QString

Lets see how we can convert enum to QString via Qt’s powerful meta object system. When a class is declared with Q_OBJECT macro Qt can query enums that are added via Q_ENUMS.
Adding your custom defined enums to Q_ENUMS, makes it available via the class’s Qt meta object.

The following code snippet declares a enum and adds to Q_ENUMS

class MyQObjectDerivedClass : public QObject

{
 Q_OBJECT;
 Q_ENUMS(RSSElement);
 public:
enum RSSElement
 {
 title,
 link,
 description,
 pubDate,
 language,
 lastBuildDate,
 category
 };
// Add to meta system
 ....
 };

Now get meta object and look for index of the enum name.

int index = metaObject()->indexOfEnumerator("RSSElement");

We got the enumerator index we are intrested in. Get the meta properties of enum by

QMetaEnum metaEnum = metaObject()->enumerator(index);

Now look for the value we are intrested in i.e., title,link,description etc

metaEnum.valueToKey();

A short code snippet will look like…

RSSElement element = title;
 QString valueInString = enumToString(element);
 // valueInString holds "title"
 ...
 QString MyQObjectDerivedClass::enumToString(RSSElement aElement)
 {
 int index = metaObject()->indexOfEnumerator("RSSElement");
 QMetaEnum metaEnum = metaObject()->enumerator(index);
 return metaEnum.valueToKey(aElement);
 }

Epilogue : Thanks to Qt Meta System!

Advertisements

2 thoughts on “Convert Enum to QString

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s