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

Dan Milburn danmilburn at clara.co.uk
Mon Jul 5 18:10:57 CEST 2010


Mandeep Sandhu wrote:
> Hi All,
> 
> Is there a way to programmatically  instantiate a class given it's name?
> 
> Eg: I'm making a library which calls upon other helper classes to do
> the actual job. So a user calls a method say - setHelper(QString
> helpername) in this lib, and the lib internally instantiates an object
> of a class who's name is specified in "helpername". I'll have the
> "helper" classes follow a set interface so that my lib routines have a
> uniform way of interacting with all such helpers.
> 
> 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>();

Dan



More information about the Qt-interest-old mailing list