PDA

View Full Version : Does Qt provide a mechanism to instantiate an object by name (string)?



fonzi337
11th February 2012, 02:28
I'm wondering if Qt (perhaps through the meta-object system) provides a mechanism to instantiate a QObject-derived object simply by specifying the type's name. The use case here would be to read a class' name from a configuration file and instantiate the appropriate type (without having messy if...else if...else logic). The QMetaObject documentation shows there is a newInstance() method, but that doesn't quite do what I'm looking for (i.e., creating an object from a string name).

MarekR22
11th February 2012, 19:37
Yes it does, read manual about QMetaType::details. First example shows how to do it.

fonzi337
11th February 2012, 20:19
Excellent, thank you very much!

Alir3z4
11th February 2012, 20:46
What about template programming ?

fonzi337
13th February 2012, 20:00
Alir3z4, could you share your thoughts on how you would use template programming to accomplish this? If one is reading information (strings) from a configuration file, I'm not sure how template programming can help to get around having if...else if...else logic to instantiate the appropriate templated-type. How were you thinking of using templates for this?

Alir3z4
14th February 2012, 21:54
Oh, i misunderstood by it, i tought you mean by the type, but as you mentioned creating an object from a string name
;)