Enums in QT
-
Hi, I have 4 enums in Code like and there messages.
enum A { Message1=0; } enum B{ Message2=1; } enum C { Message3=2; } enum D { Message4=3; }
Now my Question How can i Defined Generic Method which can take Parameter/Argument as Any enum like A,B,C,D.
Currently I am Doing this
void CommonApi(Qvariant message) { qDebug()<<message; }
But its Printing Enum Values like 0,1,2,etc.
If i do seperately like
void Api1(classname::A message) { qDebug()<<message; } void Api2(classname::B message) { qDebug()<<message; } void Api3(classname::C message) { qDebug()<<message; } void Api4(classname::D message) { qDebug()<<message; }
Then all above is printing Respective Messages. But this is seprate method, i want generic one !
-
What happens when you change the enums into
enum class
?enum class A { Message1=0 }; // ... etc.
The reason why it does not work for QVariant is that enums are really just integers. A generic method does not know which enum did the number come from. So I don't think this can be done with enums in a generic way. That is not what enums are for.
-
What happens when you change the enums into
enum class
?enum class A { Message1=0 }; // ... etc.
The reason why it does not work for QVariant is that enums are really just integers. A generic method does not know which enum did the number come from. So I don't think this can be done with enums in a generic way. That is not what enums are for.
@sierdzio Okay, Can you suggest me some alternative for this ?
-
What do you want to achieve? Have some predefined messages? Then you can use a global header where you define them, like:
namespace Tags { const char *Name1 = "Some string"; const char *Name2 = "Some other string"; };
If you need to stringify enum names, you can use QMetaEnum like this:
class Enums { Q_GADGET enum A { Message1, Message2 } Q_ENUM(A); QString aToString(const A value) { const QMetaEnum metaEnum(QMetaEnum::fromType<Enums::A>()); const QString name(metaEnum.valueToKey(int(value))); return name; } }