首页 > 代码库 > QT下 enum转QString

QT下 enum转QString

先在QT5.7

class EnumTest :public QObject
{
    Q_OBJECT
public:
    EnumTest();
    enum  PINYINENUM
    {
        XYDA,
        XYDB,
        XYDC,
        XYDD
    };
    Q_ENUM(PINYINENUM)
    static QString getPinYin(int pinYinID);
};
#include "enumtest.h"

EnumTest::EnumTest()
{

}

QString EnumTest::getPinYin(int pinYinID)
{
    QMetaEnum metaEnum = QMetaEnum::fromType<EnumTest::PINYINENUM>();
    const char* pinYinChars=metaEnum.valueToKey(pinYinID);
    QString result(pinYinChars);
    return result;
}
#include <QCoreApplication>

#include "enumtest.h"
#include <QDebug>


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug()<<EnumTest::getPinYin( 1);

    return a.exec();
}

 

技术分享

编译到开发板上,报错

enumtest.h: error: ISO C++ forbids declaration of ‘Q_ENUM‘ with no type [-fpermissive]
Q_ENUM(PINYINENUM)
开发板上QT版本5.2,没有这个Q_ENUM,只能另改方法

换成下下面的

class EnumTest :public QObject
{
    Q_OBJECT
public:
    EnumTest();
    enum  PINYINENUM
    {
        XYDA,
        XYDB,
        XYDC,
        XYDD
    };
    Q_ENUMS(PINYINENUM)
    static QString getPinYin(int pinYinID);
};
#include "enumtest.h"

EnumTest::EnumTest()
{

}

QString EnumTest::getPinYin(int pinYinID)
{
    const QMetaObject metaObject = EnumTest::staticMetaObject;
    int enumIndex = metaObject.indexOfEnumerator("PINYINENUM");
    if(enumIndex == -1) {
        
        qDebug()<< "";
    }
    QMetaEnum en = metaObject.enumerator(enumIndex);
    return  QString(en.valueToKey(pinYinID));

}
#include <QCoreApplication>

#include "enumtest.h"
#include <QDebug>
void readData();

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug()<<EnumTest::getPinYin(1);

    return a.exec();
}

技术分享

编译通过。

 

QT下 enum转QString