2010-04-01 204 views
4

我在頭文件中註冊了枚舉類型「ClefType」 - 此枚舉使用Q_DECLARE_METATYPE和Q_ENUMS宏在MetaObject系統中註冊。 qRegisterMetaType也在類構造函數中調用。訪問存儲在QVariant中的枚舉

這使我可以在Q_PROPERTY中使用這種類型,這一切都很好。然而,稍後,我需要能夠獲得這個枚舉類型的Q_PROPERTY,給定對象 - 以適合序列化的形式。

理想情況下,爲該枚舉成員存儲整數值將是有用的,因爲我不希望這是特定於使用的枚舉類型 - 最終我想要有幾個不同的枚舉

// 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? 

不幸的是variantValue.toInt();不起作用 - 自定義枚舉似乎沒有直接「澆注料」爲整數值。

由於提前,

亨利

回答

0

您可以使用>><<運營商的QVariant的做到這一點。

儲蓄(其中MyClass *x = new MyClass(this);outQDataStream):

const QMetaObject *pObj = x->pObj(); 
for(int id = pObj->propertyOffset(); id < pObj->propertyCount(); ++id) 
{ 
    QMetaProperty pMeta = pObj->property(id); 
    if(pMeta.isReadable() && pMeta.isWritable() && pMeta.isValid()) 
    { 
     QVariant variantValue = pMeta.read(x); 
     out << variantValue; 
    } 
} 

加載:

const QMetaObject *pObj = x->pObj(); 
for(int id = pObj->propertyOffset(); id < pObj->propertyCount(); ++id) 
{ 
    QMetaProperty pMeta = pObj->property(id); 
    if(pMeta.isReadable() && pMeta.isWritable() && pMeta.isValid()) 
    { 
     QVariant variantValue; 
     in >> variantValue; 
     pMeta.write(x, variantValue); 
    } 
} 

您需要調用

qRegisterMetaType<CMyClass::ClefType>("ClefType"); 
    qRegisterMetaTypeStreamOperators<int>("ClefType"); 

除了使用Q_OBJECTQ_ENUMSQ_PROPERTY。調用qRegisterMetaTypeStreamOperators<int>告訴Qt使用int版本的operator<<operator>>

順便說一下:使用qRegisterMetaType<CMyClass::ClefType>()而不是名稱形式不適用於我。如果您使用返回的ID來查找名稱,可能會更容易。

僅供參考,這裏是MyClass定義:

class CMyClass : public QObject 
{ 
    Q_OBJECT 
    Q_ENUMS(ClefType) 
    Q_PROPERTY(ClefType cleftype READ getCleftype WRITE setCleftype) 
public: 
    CMyClass(QObject *parent) : QObject(parent), m_cleftype(One) 
    { 
     qRegisterMetaType<CMyClass::ClefType>("ClefType"); 
     qRegisterMetaTypeStreamOperators<int>("ClefType"); 
    } 
    enum ClefType { Zero, One, Two, Three }; 
    void setCleftype(ClefType t) { m_cleftype = t; } 
    ClefType getCleftype() const { return m_cleftype; } 
private: 
    ClefType m_cleftype; 
}; 

Q_DECLARE_METATYPE(CMyClass::ClefType) 
+0

效果很好 - 非常感謝您的深入響應!非常感激 – 2010-04-07 10:06:53

1

嘗試:

int x = variantValue.value<ClefType>(); 
+0

雖然這會工作特別是對於ClefType,理想情況下我喜歡這種方式適用於任何枚舉類型。 – 2010-04-01 19:50:08

1

我有同樣的問題,並與下面的解決方案,它適用於任何枚舉類型上來:

int x = property.enumerator().value(*reinterpret_cast<const int *>(variantValue.constData()));