-
-
Save ruisebastiao/2c82adb86a29989283b600cd14c916c4 to your computer and use it in GitHub Desktop.
QMetaEnum: Serializing C++ Enums
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const QString Item::type() const | |
{ | |
const QMetaObject &mo = Item::staticMetaObject; | |
int index = mo.indexOfEnumerator("Type"); | |
QMetaEnum metaEnum = mo.enumerator(index); | |
return metaEnum.valueToKey(m_type); | |
} | |
void Item::setType(const QString &type) | |
{ | |
const QMetaObject &mo = Item::staticMetaObject; | |
int index = mo.indexOfEnumerator("Type"); | |
QMetaEnum metaEnum = mo.enumerator(index); | |
int value = metaEnum.keyToValue(qPrintable(type)); | |
m_type = static_cast<Type>(value); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Item | |
{ | |
public: | |
enum Type { | |
CAR, | |
BIRD, | |
APPLE | |
}; | |
public: | |
explicit Item(); | |
const QString type() const; | |
void setType(enum Type type); | |
void setType(const QString &type); | |
private: | |
enum Type m_type = Item::APPLE; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QObject> | |
class Item | |
{ | |
Q_GADGET | |
Q_ENUMS(Type) | |
public: | |
enum Type { | |
CAR, | |
BIRD, | |
APPLE | |
}; | |
explicit Item(); | |
const QString type(); | |
void setType(enum Type type); | |
void setType(const QString &type); | |
private: | |
enum Type m_type = Item::APPLE; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QDebug> | |
#include "item.h" | |
int main(int argc, char *argv[]) | |
{ | |
Q_UNUSED(argc) | |
Q_UNUSED(argv) | |
Item item; | |
qDebug() << item.type(); | |
item.setType(Item::CAR); | |
qDebug() << item.type(); | |
item.setType("BIRD"); | |
qDebug() << item.type(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment