头文件中定义枚举类型并设置Q_ENUMS
#ifndef TEST_H#define TEST_H
#include <QObject>#include <QMetaEnum>
class Test : public QObject{ Q_OBJECT Q_ENUMS(TestType) //[1]
public: explicit Test(QObject *parent = nullptr);
enum TestType { TEST_ONE, TEST_TWO, TEST_THREE };
signals:
public slots: void DoTest(QString command);};
#endif // TEST_H
源文件中的调用方式:
#include "test.h"#include <QDebug>
Test::Test(QObject *parent) : QObject(parent){
}
void Test::DoTest(QString command){//[2] QMetaObject是用来保存Qt元对象的元信息,当继承QObject类并使用宏Q_OBJECT时,创建的类产生一个静态QMetaObject实例staticMetaObject,这个实例会保存类名、信号名称及索引、槽的名字及索引等等在对象操作时需要的基本信息
QMetaObject object = this->staticMetaObject; QMetaEnum MeteEnum = object.enumerator( object.indexOfEnumerator("Tests")); //[3] switch (MeteEnum.keysToValue(command.toLatin1())) //[4] { case TEST_ONE: qDebug() << "TEST 1"; break; case TEST_TWO: qDebug() << "TEST 2"; break; case TEST_THREE: qDebug() << "TEST 3"; break; default: qDebug() << "TEST NONE"; break; }}
测试程序调用类:
#include <QCoreApplication>#include "test.h"
int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); Test cTest; cTest.DoTest(QString("sfe")); cTest.DoTest(QString("TEST1")); return a.exec();}
转载于:https://www.cnblogs.com/svenzhang9527/p/10806957.html