Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading/writing QObjects

Tags:

c++

file-io

qt

I think I can write a QObject like this by taking advantage of the Q_PROPERTYs:

QDataStream &operator<<(QDataStream &ds, const Object &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;
}

Which, if that's true, I don't know why QObjects don't already have that method implemented because it's pretty generic. But that's besides the point. How would I read the file? i.e., implement this function?

QDataStream &operator>>(QDataStream &ds, Object &obj) {
    return ds;
}

I'm thinking I can somehow use ds.readBytes but how would I get the length of the property?

PS: If it wasn't obvious, Object is my custom class that inherits from QObject.

like image 752
mpen Avatar asked Sep 13 '09 23:09

mpen


People also ask

What is a QObject?

QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect().

What is Q_PROPERTY in QML?

Exposing Properties. A property can be specified for any QObject-derived class using the Q_PROPERTY() macro. A property is a class data member with an associated read function and optional write function. All properties of a QObject-derived or Q_GADGET class are accessible from QML.

What is QObject :: connect?

To connect the signal to the slot, we use QObject::connect(). There are several ways to connect signal and slots. The first is to use function pointers: connect(sender, &QObject::destroyed, this, &MyObject::objectDestroyed); There are several advantages to using QObject::connect() with function pointers.

What is property in Qt?

The property type can be any type supported by QVariant, or it can be a user-defined type. In this example, class QDate is considered to be a user-defined type. Q_PROPERTY(QDate date READ getDate WRITE setDate) Because QDate is user-defined, you must include the <QDate> header file with the property declaration.


1 Answers

This seems to work.

QDataStream &operator>>(QDataStream &ds, Object &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;
}

Thanks to Eugene.

like image 109
mpen Avatar answered Sep 28 '22 12:09

mpen