Qt5.5中类反射试验

网络上下载的类:
#ifndef OBJECTFACTORY_H
#define OBJECTFACTORY_H


class ObjectFactory
{
public:
  template<typename T>
  static void registerClass()
  {
    constructors().insert( T::staticMetaObject.className(), &constructorHelper<T> );
  }


  static QObject* createObject( const QByteArray& className, QObject* parent = NULL )
  {
    Constructor constructor = constructors().value( className );
    if ( constructor == NULL )
      return NULL;
    return (*constructor)( parent );
  }


private:
  typedef QObject* (*Constructor)( QObject* parent );


  template<typename T>
  static QObject* constructorHelper( QObject* parent )
  {
    return new T( parent );
  }


  static QHash<QByteArray, Constructor>& constructors()
  {
    static QHash<QByteArray, Constructor> instance;
    return instance;
  }
};


#endif // OBJECTFACTORY_H




自己建立的测试类:
#ifndef CDXOBJECT_H
#define CDXOBJECT_H


#include <QObject>


#include "QString"


class CdxObject : public QObject
{
    Q_OBJECT


public:
    QString m_sName;


public:
    explicit CdxObject(QObject *parent = 0);


signals:


public slots:


};




class CdxDrawObject : public CdxObject
{
    Q_OBJECT


public:
    explicit CdxDrawObject(QObject* parent);


signals:


public slots:


};


class CdxNetworkObject : public CdxObject
{
    Q_OBJECT


public:
    explicit CdxNetworkObject(QObject* parent);


signals:


public slots:


};


#endif // CDXOBJECT_H




//cdxobject.cpp
#include "cdxobject.h"


CdxObject::CdxObject(QObject *parent) : QObject(parent)
{
    m_sName="root object";
}


CdxDrawObject::CdxDrawObject(QObject* parent)
{
    m_sName="draw object";
}


CdxNetworkObject::CdxNetworkObject(QObject* parent)
{
    m_sName="network object";
}


//调用测试


#include "cdxobject.h"
#include "objectfactory.h"


void MainWindow::on_pushButton_clicked()
{
    ObjectFactory::registerClass<CdxObject>();
    ObjectFactory::registerClass<CdxDrawObject>();
    ObjectFactory::registerClass<CdxNetworkObject>();


    //CdxObject* object = (CdxObject*)ObjectFactory::createObject( "CdxObject" );
    //CdxObject* object = (CdxObject*)ObjectFactory::createObject( "CdxDrawObject" );
    CdxObject* object = (CdxObject*)ObjectFactory::createObject( "CdxNetworkObject" );


    ui->lineEdit->setText(object->m_sName);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值