我一直在尝试导出一些QFlags用于QML(主要是从QML中公开的对象的属性中读取它们),但即使在this SO question之后,我仍然会遇到编译器错误:
#ifndef HOLIDAYACTIVITIES_H
#define HOLIDAYACTIVITIES_H
#include <QObject>
#include <QMetaType>
#include <QPair>
#include <QObject>
#include <QDateTime>
#include <QGeoLocation>
namespace HolidayPlanner
{
class Holiday: public QObject {
Q_OBJECT
Q_ENUMS(ActivityType)
Q_ENUMS(TransportType)
public:
explicit Holiday(QObject* parent = 0);
virtual ~Holiday();
enum ActivityType {
Transportation = 1,
Lodging = 2,
Sights = 4,
Note = 8,
Food = 16
};
enum TransportType {
Flight = 1,
Train = 2,
Subway = 4,
Bus = 8,
Foot = 16,
Other = 32,
None = 64
};
enum ItemRole {
TypeRole = Qt::UserRole + 1000,
StartDateRole = Qt::UserRole + 1001,
EndDateRole = Qt::UserRole + 1002,
StartPositionRole = Qt::UserRole + 1003,
EndPositionRole = Qt::UserRole + 1004,
TaskRole = Qt::UserRole + 1005,
};
Q_DECLARE_FLAGS(ActivityTypes, ActivityType)
Q_FLAGS(ActivityTypes)
Q_DECLARE_FLAGS(TransportTypes, TransportType)
Q_FLAGS(ActivityTypes)
};
Q_DECLARE_OPERATORS_FOR_FLAGS(Holiday::ActivityTypes)
Q_DECLARE_OPERATORS_FOR_FLAGS(Holiday::TransportTypes)
}; // namespace HolidayPlanner
Q_DECLARE_METATYPE(HolidayPlanner::Holiday::ActivityType)
Q_DECLARE_METATYPE(HolidayPlanner::Holiday::TransportType)
但是当我发出
时qmlRegisterType<HolidayPlanner::Holiday::ActivityType>();
代码中的任何地方,我都会
In file included from /usr/include/qt5/QtQml/QtQml:9:0,
from /home/lb/Coding/cpp/holiday-planner/src/holidayactivities.cpp:21:
/usr/include/qt5/QtQml/qqml.h: In instantiation of ‘int qmlRegisterType() [with T =
HolidayPlanner::Holiday::ActivityType]’:
/home/lb/Coding/cpp/holiday-planner/src/holidayactivities.cpp:28:60: required from here
/usr/include/qt5/QtQml/qqml.h:109:5: error: ‘staticMetaObject’ is not a member of
‘HolidayPlanner::Holiday::ActivityType’
QML_GETTYPENAMES
^
/usr/include/qt5/QtQml/qqml.h:119:21: error: ‘staticMetaObject’ is not a member of
‘HolidayPlanner::Holiday::ActivityType’
0, 0, 0, 0, &T::staticMetaObject,
^
这里可能出现什么问题?
作为参考,像QLocale这样的其他类可以将它们的枚举导出到QML(默认情况下没有完成,但是它有效),但是我无法找到任何关于它为什么在我的情况下不起作用的线索。
答案 0 :(得分:2)
您无法将枚举注册为qml类型。 qmlRegisterType<T>()
函数仅适用于从QObject派生的类。 AFAIK注册enumus不是必需的。他们被视为正常的整体。
为了能够将QObject
中QVariant
以内未导出的所有其他类型传递给qml,请使用qRegisterMetaType<T>
。你不能直接在qml中使用它们,但你可以传递给C ++槽,属性和可调用的方法。
答案 1 :(得分:1)
你可能没有正确地这样做。您需要注册包含枚举的类,然后它将自动可用。以下是一般情况的示例:
class MyClass : public QObject
{
Q_OBJECT
Q_ENUMS(MyEnum)
Q_PROPERTY(MyEnum myEnum READ myEnum)
public:
enum MyEnum {
Value1 = 0,
Value2
};
explicit MyObject(QObject *parent = 0);
MyEnum myEnum() const;
Q_INVOKABLE MyEnum getMyEnum() const;
};
qmlRegisterType<MyClass>("myclass", 1, 0, "MyClass");
要根据您的具体情况进行解释,您可能会写下这样的内容:
qmlRegisterType<Holiday>("holiday", 1, 0, "Holiday");
然后,您将从QML访问枚举值,如下所示:
holiday.Transportation