在Qt中序列化我的自定义类

时间:2012-12-12 07:54:50

标签: c++ qt serialization qobject

我使用Reading/writing QObjects 这是真的吗? 我用它序列化一个类,但是当反序列化它不是原始类!

我能做什么?

这是我的基类标题:

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) ;

和.cpp是:

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;
}

我有一个继承自base的学生班:

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

这是我的主要内容:

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();
}

这是我的输出:

30 "erfan" 
1498018562 "" 
1498018562 ""

1 个答案:

答案 0 :(得分:15)

您必须将idName设为Q_PROPERTY才能使用metaObject属性系统处理它:

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;
};

现在应该以适当的方式处理属性。

有关详细信息,请参阅http://doc.qt.io/qt-5/properties.html