I have registered an enumeration type “ClefType” within my header file – this enum is registered with the MetaObject system using the Q_DECLARE_METATYPE and Q_ENUMS macros. qRegisterMetaType is also called in the class constructor.
This allows me to use this type in a Q_PROPERTY, this all works fine. However, later on, I need to be able to get hold of the Q_PROPERTY of this enum type, given the object – in a form that is suitable for serialization.
Ideally, it would be useful to store the integer value for that enum member, because I don’t want this to be specific to the type of enum that is used – eventually I want to have several different enums.
// This is inside a loop over all the properties on a given object
QMetaProperty property = metaObject->property(propertyId);
QString propertyName = propertyMeta.name();
QVariant variantValue = propertyMeta.read(serializeObject);
// If, internally, this QVariant is of type 'ClefType',
// how do I pull out the integer value for this enum?
Unfortunately variantValue.toInt(); does not work – custom enums don’t seem to be directly ‘castable’ to an integer value.
Thanks in advance,
Henry
You can use the
>>and<<operators of QVariant to accomplish this.Saving (where
MyClass *x = new MyClass(this);andoutis aQDataStream):Loading:
You will need to call
in addition to using
Q_OBJECT,Q_ENUMSandQ_PROPERTY. CallingqRegisterMetaTypeStreamOperators<int>tells Qt to use the int versions ofoperator<<andoperator>>.By the way: using
qRegisterMetaType<CMyClass::ClefType>()instead of the form that takes a name doesn’t work for me. It might if you used the returned id to lookup the name, but this is much easier.FYI, here is the
MyClassdefinition: