How to convert enum to QString?

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

turns enum into string:

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

Perhaps you don't need QMetaEnum anymore.

Sample code here:

ModelApple (no need to claim 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 :

#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.


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

Tags:

C++

Enums

Qt