[Qt-interest] Dynamically instantiate a class using the class name

Mandeep Sandhu mandeepsandhu.chd at gmail.com
Tue Jul 6 07:32:27 CEST 2010


>> Does the QT meta system provide such a feature?
>>
>> In java, Class.forName(String className) provides this functionality.
>> Is there something similar in QT too?
>
> QMetaObject can be of some help here, but there's no way to do it
> automatically.
>
> What you would need to do is use the Q_INVOKABLE macro on the
> constructors of your objects.  You can then use
> QMetaObject::newInstance() to create the object.
>
> A factory class might then look like:
>
> class ObjectFactory
> {
> private:
>   QHash<QByteArray,const QMetaObject*> metaObjects;
>
> public:
>   template<class T>
>   void registerObject()
>   {
>     metaObjects.insert( T::staticMetaObject.className(),
> &(T::staticMetaObject) );
>   }
>
>   QObject *createObject( const QByteArray &type )
>   {
>     const QMetaObject *meta = metaObjects.value( type );
>     return meta ? meta->newInstance() : 0;
>   }
> }
>
> and you can register a class with:
>
> ObjectFactory factory;
> factory.registerObject<MyObject>();

Thanks Dan. I'll try out this approach.

Regards,
-mandeep

>
> Dan
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>




More information about the Qt-interest-old mailing list