18

我使用读/写 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 ""
4

1 回答 1

15

您必须将idandName作为 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

于 2012-12-12T08:12:52.093 回答