Skip to content

Instantly share code, notes, and snippets.

@austriancoder
Created May 2, 2016 07:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save austriancoder/9bb0c0782aafa4bb1dbcc653e9442a33 to your computer and use it in GitHub Desktop.
Save austriancoder/9bb0c0782aafa4bb1dbcc653e9442a33 to your computer and use it in GitHub Desktop.
QMetaEnum: Serializing C++ Enums
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);
}
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;
};
#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;
};
#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