Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert enum to QString?

Tags:

c++

enums

qt

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

like image 576
JustWe Avatar asked Dec 15 '15 05:12

JustWe


People also ask

How do you convert a string value to a specific enum type in C#?

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 .

What is enum in Qt?

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.

How do you print an enum in Python?

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.

What are enum types?

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.


1 Answers

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)); } 
like image 111
Meefte Avatar answered Oct 03 '22 10:10

Meefte