I am trying to use the Qt reflection for converting enum to QString.
Here is the part of code:
class ModelApple { Q_GADGET Q_ENUMS(AppleType) public: enum AppleType { Big, Small } } And here is i trying to do:
convertEnumToQString(ModelApple::Big) Return "Big"
Is this possible? If you have any idea about convertEnumToQString, please share it
TryParse() method converts the string representation of enum member name or numeric value to an equivalent enum object. The Enum. TryParse() method returns a boolean to indicate whether the specified string is converted to enum or not. Returns true if the conversion succeeded; otherwise, returns false .
An enumerated type, or enum, is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type. Enums are incredibly useful when portraying status, options, or modes that are exclusive within a grouping.
We can access the enum members by using the dot operator(.) with the enum class name. repr() : The repr() method used to print enum member. type(): This is used to print the type of enum member.
Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.
You need to use Q_ENUM macro, which registers an enum type with the meta-object system.
enum AppleType { Big, Small }; Q_ENUM(AppleType) And now you can use the QMetaEnum class to access meta-data about an enumerator.
QMetaEnum metaEnum = QMetaEnum::fromType<ModelApple::AppleType>(); qDebug() << metaEnum.valueToKey(ModelApple::Big); Here is a generic template for such utility:
template<typename QEnum> std::string QtEnumToString (const QEnum value) { return std::string(QMetaEnum::fromType<QEnum>().valueToKey(value)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With