更優雅的方式發現(QT 5.9),只是一個單一的線,具有強大的QVariant的幫助。
變成枚舉轉換爲字符串:
QString theBig = QVariant::fromValue(ModelApple::Big).value<QString>();
也許你並不需要QMetaEnum了。
示例代碼在這裏:
ModelApple(無需要求Q_DECLARE_METATYE)
class ModelApple : public QObject
{
Q_OBJECT
public:
enum AppleType {
Big,
Small
};
Q_ENUM(AppleType)
explicit ModelApple(QObject *parent = nullptr);
};
我創建窗件應用程序,調用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).value<QString>();
qDebug() << s;
}
MainWindow::~MainWindow()
{
delete ui;
}
你可以看到,我嘗試在控制檯上輸出字符串,這確實是:
對於反向鑄造抱歉,我在某些項目中嘗試成功,但是這次我遇到了編譯錯誤。所以我決定從我的答案中刪除它。
'QMetaEnum :: fromType'可從Qt 5中獲得,它在Qt 4中不存在。您應該添加此註釋。順便說一下,我不推薦使用'QMetaEnum :: key',因爲它將'index'作爲參數,他怎麼會聲明'enum AppleType {Big = 2,Small}' –
Danh
從文檔看來,它看起來像這實際上僅在Qt 5.5中可用,因此我仍然需要在我給出的答案(即將更新我的代碼但現在必須使用Qt 5.4)中使用我的方法。 –