[Interest] How to create QObject-derived class instance from class name

Sina Dogru sinadooru at gmail.com
Thu Mar 3 08:32:53 CET 2016


> > Ah you mean by "knowing types at compile time" is actually defined
> types, so you actually defining classes at run-time?
> Sina,
> No, I didn't mean that. You can't define classes at runtime as C++ is not
> a dynamic language.
>

Yeah, but sometimes qt makes me confuse, reflection was also not possible
with C++ but it is with qt :).


> I had an issue similar to your own - I wanted to write an object to a byte
> array, send it through the network, and then recreate the object at the
> other end. So one option is to have a factory class that know every
> possible object that can be send, writes a number or a string, then the
> object writes its data; send it through the network and at the other end -
> read the number/string, create the object and then call the function on
> that object (typically a virtual one) that reads the object's data. The
> thing is, for me this whole write-send-read thing is in a dynamic library
> and the classes that are serialized/deserialized are defined in the user
> application, so the library doesn't know in advance what possible classes
> the user might have defined, only that they have a common ancestor. So
> instead of making my own registration, I used Qt's QMetaType class.
>

Our cases are actually almost same, maybe the only the difference is my
objects are QObject-derived but this issue was already solved on early of
this thread.

>
> Long story short:
> When I have to serialize the object, I'm retrieving the appropriate
> QMetaObject, getting the class name from it and then I'm using
> QMetaType::type to retrieve the corresponding meta-type id. This integer I
> write in the byte stream, and then, I'm calling the object's virtual
> serialize method with the byte array (so it can write its data).
> On the other end I'm reading the integer, checking if this meta-type id is
> registered with QMetaType::isRegistered and then I'm using
> QMetaType::create with said meta-type id to create the correct instance.
> I'm casting the void * that the creation method returns to a base class
> pointer and calling the virtual deserialize method (so the object can read
> it's data).
>
> Here's a thread I started in the Qt forum some time ago, which could be
> useful if you decide to have your objects marshaled in a similar manner:
> https://forum.qt.io/topic/64277/meta-type-id-of-an-object
>

But I thank for you to writing, I guess at that point I have enough
material to overcome this! I will study on this thread.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20160303/34058f6b/attachment.html>


More information about the Interest mailing list