tags:

views:

316

answers:

1

I think I can write a QObject like this by taking advantage of the Q_PROPERTYs:

QDataStream &operator<<(QDataStream &ds, const Object &obj) {
    for(int i=0; i<obj.metaObject()->propertyCount(); ++i) {
        if(obj.metaObject()->property(i).isStored(&obj)) {
            ds << obj.metaObject()->property(i).read(&obj);
        }
    }
    return ds;
}

Which, if that's true, I don't know why QObjects don't already have that method implemented because it's pretty generic. But that's besides the point. How would I read the file? i.e., implement this function?

QDataStream &operator>>(QDataStream &ds, Object &obj) {
    return ds;
}

I'm thinking I can somehow use ds.readBytes but how would I get the length of the property?

PS: If it wasn't obvious, Object is my custom class that inherits from QObject.

A: 

This seems to work.

QDataStream &operator>>(QDataStream &ds, Object &obj) {
    QVariant var;
    for(int i=0; i<obj.metaObject()->propertyCount(); ++i) {
        if(obj.metaObject()->property(i).isStored(&obj)) {
            ds >> var;
            obj.metaObject()->property(i).write(&obj, var);
        }
    }
    return ds;
}

Thanks to Eugene.

Mark