我正在对 Qt 的元对象系统进行一些修改,并且遇到了添加enum class
到元对象的问题。我有一个包含一些变量的结构,其中一个是enum class
.
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <QObject>
enum class CarType {
NO_CAR = 0,
SLOW_CAR,
FAST_CAR,
HYPER_CAR
};
struct Player {
Q_GADGET
Q_PROPERTY(Player player READ getPlayer)
Q_PROPERTY(float m_speed READ getSpeed)
Q_PROPERTY(CarType m_carType READ getCarType)
Player getPlayer() { return *this;}
float getSpeed() {return m_speed;}
CarType getCarType() { return m_carType;}
public:
CarType m_carType;
float m_speed;
}; Q_DECLARE_METATYPE(Player)
#endif // EXAMPLE_H
我将此结构声明为 a Q_META_TYPE
,以便使用元对象系统访问它。这允许我访问结构的属性。这是我的main.cpp
:
#include <QCoreApplication>
#include <iostream>
#include <QMetaObject>
#include "example.h"
#include <QDebug>
#include <QMetaProperty>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qRegisterMetaType<Player>();
const QMetaObject* metaObject = &Player::staticMetaObject;
qInfo()<< "Number of enums is: " << metaObject->enumeratorCount();
return a.exec();
}
我希望这enumeratorCount()
将是 1,但我得到 0。我已经搜索过这个问题,我能找到的大多数示例都有一个类中的结构,以及紧随其后的Q_ENUM
声明,如下所示:
enum class CarType {
NO_CAR = 0,
SLOW_CAR,
FAST_CAR,
HYPER_CAR
}; Q_ENUM(CarType)
但是,这会导致错误。在元对象系统中注册这个枚举的正确方法是什么?
谢谢你的时间。
编辑 我得到的相关错误是:
/home/raphael/SO_Example/example.h:10: error: ‘friend’ used outside of class
/home/raphael/SO_Example/example.h:10: error: ‘staticMetaObject’ was not declared in this scope; did you mean ‘qt_getQtMetaObject’?