-
Notifications
You must be signed in to change notification settings - Fork 68
Polymorphic Q_GADGETs #8
Comments
With the current implementation, this is not directly possible. The reason is that gadgets are value types and c++ can simply not handle polymorphism for value types correctly. Also, gadgets do not have a non-static metaobject associated, which means it's impossible to dynamically detect their type. However, if you are fine with a workaround, I guess the following would work: Assuming you have the following (simplified) classes: class GadgetBase {
//...
};
class Gadget1 : public GadgetBase {
// ...
};
class Gadget2 : public GadgetBase {
// ...
};
class SomeOtherGadget {
GadgetBase *theGadget; //should be either 1 or 2
}; You could implement SomeOtherGadget as follows: class SomeOtherGadget {
Q_GADGET
Q_PROPERTY(QJsonObject theGadget READ getGad WRITE setGad)
GadgetBase *theGadget;
QJsonSerializer *serializer;
SomeOtherGadget() {
serializer = // get the serializer somehow or just create a new one
}
QJsonObject getGad() const {
QJsonObject obj;
QString type = getGadgetClassName(theGadget);
if(type == "Gadget1")
obj = serializer->serialize(*static_cast<Gadget1*>(theGadget));
else if(type == "Gadget2")
obj = serializer->serialize(*static_cast<Gadget2*>(theGadget));
// ...
obj["@class"] = type;
return obj;
}
void setGad(const QJsonObject &obj) {
if(obj["@class"] == "Gadget1")
theGadget = new Gadget1(serializer->deserialize<Gadget1>(obj)); //copy-construct to the heap
else if(obj["@class"] == "Gadget2")
theGadget = new Gadget2(serializer->deserialize<Gadget2>(obj)); //copy-construct to the heap
// ...
}
}; It's a little complicated and verbose, but more or less the only way to make gadget serialization "polymorphic" (I used a special property name |
Another alternative would be to implement a custom |
Thank you for your huge reply. I suppose that you code sample will be helpful for other users too. |
Hello! Do you have any hints concerning (de-)serialization of polymorphic Q_GADGETs? They can also have Q_CLASSINFO. I suppose that I have to create a "switch" for property getter/setter which checks some flag in JSON. It will choose, in fact, among
variant.value<Class1>()
,variant.value<Class2>()
and so on for deserialization.The text was updated successfully, but these errors were encountered: