I think I can write a QObject
like this by taking advantage of the Q_PROPERTY
s:
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 QObject
s 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
.
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().
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With