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()); ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.