[Qt-interest] How to create object instance knowing only its class name in a QString?
frares at gmail.com
frares at gmail.com
Mon Jan 30 14:45:42 CET 2012
On , Mandeep Sandhu <mandeepsandhu.chd at gmail.com> wrote:
> 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
> void registerClass(const QString &className)
> {
> m_factoryObjects.insert(className, &(T::staticMetaObject));
> }
> template
> T* createObject(const QString &className, QObject *parent = 0)
> {
> const QMetaObject *meta = m_factoryObjects.value(className);
> return (meta ?
> qobject_cast(meta->newInstance(Q_ARG(QObject *, parent)))
> : 0);
> }
> private:
> QHash m_factoryObjects;
> };
> HTH,
> -mandeep
Thank you.
Thanks for the QHash idea, also.
Francisco
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20120130/2adaa276/attachment.html
More information about the Qt-interest-old
mailing list