PDA

View Full Version : How to convert QString to enum?



fonzi337
19th January 2012, 01:29
Hi,

I'm wondering if there is a standard method provided to convert a string to its corresponding enum. Something similar to .NET/C#'s Enum.Parse or Enum.TryParse.

Thanks!

pkj
19th January 2012, 06:11
Qt provides QMetaEnum for the purpose.

for each enum whose name you want automatically at runtime, register it with Q_ENUMS, then retrieve its name with QMetaEnum::name() and its keys' names with QMetaEnum::key().

fonzi337
20th January 2012, 19:19
Thank you pkj. Would you mind providing a brief example of how this is done in code?

Thanks!

xcxl
20th July 2018, 08:17
Hi,
I'm not an expert, but just a cast works for me, and it's easier to use if only used once in the code...



enum MyEnum {VAL_ENUM1, VAL_ENUM2};
m_variable = MyEnum(QString("1").toUInt()); // now m_variable = VAL_ENUM2


(For all people like me who search for it years after)

d_stranz
21st July 2018, 20:09
QMetaEnum is the correct way to go. QString::toUInt() works only when the name of the enum is actually its value (eg. "1" -> 1). With QMetaEnum, both the name of the enum and its value can be anything.