C++ 如何将枚举转换为 QString?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34281682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:21:31  来源:igfitidea点击:

How to convert enum to QString?

c++qtenums

提问by JustWe

I am trying to use the Qt reflection for converting enum to QString.

我正在尝试使用 Qt 反射将枚举转换为 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"

返回 "Big"

Is this possible? If you have any idea about convertEnumToQString, please share it

这可能吗?如果您有任何想法convertEnumToQString,请分享

回答by Meefte

You need to use Q_ENUMmacro, which registers an enum type with the meta-object system.

您需要使用Q_ENUM宏,它向元对象系统注册枚举类型。

enum AppleType {
  Big,
  Small
};
Q_ENUM(AppleType)

And now you can use the QMetaEnumclass to access meta-data about an enumerator.

现在您可以使用QMetaEnum类来访问有关枚举器的元数据。

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));
}

回答by Ju-Hsien Lai

Much more elegant way found (Qt 5.9), just one single line, with the help of mighty QVariant.

在强大的 QVariant 的帮助下,找到了更优雅的方式(Qt 5.9),只需一行。

turns enum into string:

将枚举转换为字符串:

QString theBig = QVariant::fromValue(ModelApple::Big).toString();

Perhaps you don't need QMetaEnum anymore.

也许您不再需要 QMetaEnum 了。

Sample code here:

示例代码在这里:

ModelApple (no need to claim Q_DECLARE_METATYE)

ModelApple(无需声明Q_DECLARE_METATYE)

class ModelApple : public QObject
{
    Q_OBJECT
public:
    enum AppleType {
      Big,
      Small
    };
    Q_ENUM(AppleType)
    explicit ModelApple(QObject *parent = nullptr);
};

And I create a widget application, calling QVaraint function there :

我创建了一个小部件应用程序,在那里调用 QVaraint 函数:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <modelapple.h>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString s = QVariant::fromValue(ModelApple::Big).toString();
    qDebug() << s;

}

MainWindow::~MainWindow()
{
    delete ui;
}

You can see that i try to output the string on console , which really did: enter image description here

您可以看到我尝试在控制台上输出字符串,确实做到了: 在此处输入图片说明

And sorry for reverse casting , i tried successfully in some project , but some how this time i met compiling error. So i decide to remove it from my answer.

很抱歉反向转换,我在某些项目中尝试成功,但这次我遇到了编译错误。所以我决定从我的答案中删除它。

回答by CJCombrink

The following should get you going:

以下应该让你开始:

QString convertEnumToQString(ModelApple::AppleType type) {
    const QMetaObject metaObject = ModelApple::staticMetaObject;
    int enumIndex = metaObject.indexOfEnumerator("AppleType");
    if(enumIndex == -1) {
        /* The enum does not contain the specified enum */
        return "";
    }
    QMetaEnum en = metaObject.enumerator(enumIndex);
    return QString(en.valueToKey(type));
}

回答by Danh

How about:

怎么样:

QString convertEnumToQString(ModelApple::AppleType type)
{
    const QMetaObject &mo = ModelApple::staticMetaObject;
    int index = mo.indexOfEnumerator("AppleType");
    QMetaEnum metaEnum = mo.enumerator(index);
    return metaEnum.valueToKey(type);
}

UPDATED:For Qt 5.5, see this answer

更新:对于 Qt 5.5,请参阅此答案

回答by secretgenes

I faced the same problem and this is how i solved it. This is especially for Qt 4.8

我遇到了同样的问题,这就是我解决它的方法。这尤其适用于Qt 4.8

QString string = enumToString(ModelApple::Big);

QString ModelApple::enumToString(AppleType apple)
{
    int index = metaObject()->indexOfEnumerator("AppleType");
    QMetaEnum metaEnum = metaObject()->enumerator(index);
    return metaEnum.valueToKey(apple);
}

回答by Alexandr Kirilov

For the global Enum declaring use this in any header file:

对于全局 Enum 声明,请在任何头文件中使用它:

namespace YourNamespace {

Q_NAMESPACE

enum YourEnum: int {

    EnumValue1,
    EnumValue2
};
Q_ENUM_NS(YourEnum)

}

and this where you want to get Enum description:

这是您想要获得 Enum 描述的地方:

QMetaEnum metaEnum = QMetaEnum::fromType<YourEnum>();
qDebug() << "Enum description: " << metaEnum.name() << "::" << metaEnum.valueToKey(YourEnum::EnumValue2);