我已经在头文件中注册了枚举类型“ClefType”-使用Q_DECLARE_METATYPE和Q_ENUMS宏在MetaObject系统中注册了该枚举。在类构造函数中也调用qRegisterMetaType。

这使我可以在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();不起作用-自定义枚举似乎不能直接“类型转换”为整数值。

提前致谢,

亨利

最佳答案

您可以使用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使用intt版本的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)

关于qt4 - 访问存储在QVariant中的枚举,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2560242/

10-11 22:40
查看更多