O'Reilly logo

Game Programming using Qt 5 Beginner's Guide - Second Edition by Lorenz Haas, Witold Wysota, Pavel Strakhov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

What just happened?

We want to use the Q_ENUM macro on our enum, because it will allow us to easily convert enum values to strings and back, which is very useful for serialization. Since InventoryItem is not a QObject, we need to add a Q_GADGET macro to the beginning of the class declaration to make the Q_ENUM macro work. Think of Q_GADGET as of a lightweight variation of Q_OBJECT that enables some of its features but not others.

The typeByName() method will receive a string and return the corresponding enum variant. We can implement this method as follows:

InventoryItem::Type InventoryItem::typeByName(const QStringRef &r) { QMetaEnum metaEnum = QMetaEnum::fromType<InventoryItem::Type>(); QByteArray latin1 = r.toLatin1(); int result = metaEnum.keyToValue(latin1.constData()); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required