简体   繁体   中英

How to serialize custom objects

I have a problem trying to serialize on disk my objects. This is a simplified scenario:

I have ObjectA providing its own serialization operators. They work since I can save/load data to file. Next I have ObjectB containing ObjectA as data member. Trying to save ObjectB I got a runtime error:

QVariant::save: unable to save type 279.

I'm using this code for stream opertors:

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

QDataStream & operator>>(QDataStream & dataStream, ObjectA & objectA) {
    QVariant var;
    for(int i=0; i < objectA.metaObject()->propertyCount(); ++i) {
        if(objectA.metaObject()->property(i).isStored(&objectA)) {
            dataStream >> var;
            objectA.metaObject()->property(i).write(&objectA, var);
        }
    }

    return dataStream;
}

(just replace A with B for ObjectB operators)

I think that the error is in ObjectB serialization implementation, but I dunno how to proceed.

You must qRegisterMetaTypeStreamOperators on your type. Eg:

class MyType {
  ...
};
Q_REGISTER_METATYPE(MyType);

int main(int argc, char ** argv) {
  ...
  qRegisterMetaTypeStreamOperators<MyType>();
  ...
}

It is no longer necessary in Qt 6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM