[Qt-interest] How to create object instance knowing only its class name in a QString?
Jason H
scorp1us at yahoo.com
Mon Jan 30 15:08:11 CET 2012
This came up for my team recently too.
What are the differences between using templates and using an approach where all classes in the factory use common base class (minimally QObject) and qobject_cast<>()?
________________________________
From: Mandeep Sandhu <mandeepsandhu.chd at gmail.com>
To: frares at gmail.com
Cc: QT Interest List <qt-interest at trolltech.com>
Sent: Monday, January 30, 2012 8:08 AM
Subject: Re: [Qt-interest] How to create object instance knowing only its class name in a QString?
On Mon, Jan 30, 2012 at 6:27 PM, <frares at gmail.com> wrote:
> Hi, all.
>
> How do I instantiate an object knowing its class name in a QString and that
> all similar classes are derived from a "facade" super class?
>
You can use the factory pattern here. The QMetaObject class is your
friend in such cases.
Eg: You can keep a map of class names to their corresponding static
meta-objects and then invoke QMetaObject::newInstance() to create an
object of that class.
Here's some sample code:
class ObjectFactory
{
public:
template<class T>
void registerClass(const QString &className)
{
m_factoryObjects.insert(className, &(T::staticMetaObject));
}
template<class T>
T* createObject(const QString &className, QObject *parent = 0)
{
const QMetaObject *meta = m_factoryObjects.value(className);
return (meta ?
qobject_cast<T *>(meta->newInstance(Q_ARG(QObject *, parent)))
: 0);
}
private:
QHash<QString, const QMetaObject *> m_factoryObjects;
};
HTH,
-mandeep
_______________________________________________
Qt-interest mailing list
Qt-interest at qt.nokia.com
http://lists.qt.nokia.com/mailman/listinfo/qt-interest
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20120130/008b2188/attachment.html
More information about the Qt-interest-old
mailing list