qtserializationqfileqiodevice

Best way to write a custom class to a file using qt


Hey all (out there :).
Which way is the best for writing a custom class to a file in Qt?
Thank you in advance.
Matthias


Solution

  • EDIT: Question has been already asked. Serialization with Qt

    The best way is to serialize using QDataStream. For a given class MyClass, you need to define new stream operators

    QDataStream &operator<<(QDataStream &, const MyClass &);
    QDataStream &operator>>(QDataStream &, MyClass &);
    

    QDataStream is already capable of writing several Qt classes, mostly collections and other convenients classes like QImage, etc.... Note that you cannot serialize any subclass of QObject. There are reasons :), but limit yourself to the explanation that QObject itself doesn't provide neither copy constructors nor in\out stream functions like the one above.

    Note that if your custom class derive a class already providing serialization, you need to call the stream operators for this superclass (the same principle as calling the constructor of the superclass when constructing the subclass).