访问存储在QVariant中的枚举

Hen*_*ker 6 qt4

我在头文件中注册了一个枚举类型"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?
Run Code Online (Sandbox Code Playgroud)

遗憾的是variantValue.toInt();不起作用 - 自定义枚举似乎不能直接"转换"为整数值.

提前致谢,

亨利

小智 1

您可以使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

加载中:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要致电

    qRegisterMetaType<CMyClass::ClefType>("ClefType");
    qRegisterMetaTypeStreamOperators<int>("ClefType");
Run Code Online (Sandbox Code Playgroud)

除了使用Q_OBJECT,Q_ENUMSQ_PROPERTY. 调用qRegisterMetaTypeStreamOperators<int>告诉 Qt 使用operator<<和的 int 版本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)
Run Code Online (Sandbox Code Playgroud)