Serializing my custom class in Qt

Erfan Tavakoli picture Erfan Tavakoli · Dec 12, 2012 · Viewed 15.1k times · Source

i use Reading/writing QObjects is it true? i serialize a class with it but when deserialize it isn't the original class!

what can i do?

this is my base class header:

class Base : public QObject
{
    Q_OBJECT
public:
    explicit Base(QObject *parent = 0);


};
QDataStream &operator<<(QDataStream &ds, const Base &obj);
QDataStream &operator>>(QDataStream &ds, Base &obj) ;

and .cpp is:

Base::Base(QObject *parent) :
    QObject(parent)
{
}
QDataStream &operator<<(QDataStream &ds, const Base &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;
}
QDataStream &operator>>(QDataStream &ds, Base &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;
}

and i have a student class that inherit from base :

class student : public Base
{
public:
    student();
    int id;
    QString Name;
};

and it is my main :

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    student G;
    student G2;
    G.id=30;
    G.Name="erfan";
    qDebug()<<G.id<<G.Name;
    QFile file("file.dat");
    file.open(QIODevice::WriteOnly);

    QDataStream out(&file);   // we will serialize the data into the file
    out <<G;
    qDebug()<<G2.id<<G2.Name;
    file.close();
    file.open(QIODevice::ReadOnly);
    out>>G2;
    qDebug()<<G2.id<<G2.Name;

    return a.exec();
}

and it is my output:

30 "erfan" 
1498018562 "" 
1498018562 ""

Answer

Kamil Klimek picture Kamil Klimek · Dec 12, 2012

You must make id and Name as Q_PROPERTY to handle it with metaObject property system:

class student : public Base
{
    Q_OBJECT // Q_OBJECT macro will take care of generating proper metaObject for your class
    Q_PROPERTY(int id READ getId WRITE setId)
    Q_PROPERTY(QString Name READ getName WRITE setName)
public:
    student();
    int getId() const { return id; }
    void setId(int newId) { id = newId; }
    QString getName() const { return Name; }
    void setName(const QString &newName) { Name = newName; }

private:
    int id;
    QString Name;
};

Now properties should be handled in proper way.

See http://doc.qt.io/qt-5/properties.html for detailed information.