How to convert enum to QString?

后端 未结 6 1119
庸人自扰
庸人自扰 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:10

    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 
    #include 
    
    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:

    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.

提交回复
热议问题