How to convert enum to QString?

后端 未结 6 1130
庸人自扰
庸人自扰 2020-12-08 06:38

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)         


        
6条回答
  •  孤街浪徒
    2020-12-08 07:26

    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();
    qDebug() << metaEnum.valueToKey(ModelApple::Big);
    

    Here is a generic template for such utility:

    template
    std::string QtEnumToString (const QEnum value)
    {
      return std::string(QMetaEnum::fromType().valueToKey(value));
    }
    

提交回复
热议问题