yhkylin-backup-tools/common/reflect.h

56 lines
1.5 KiB
C
Raw Normal View History

2022-11-01 10:40:05 +08:00
/**
* brief
* author
* note :
* 1QObject或其派生数的上层节点包含QObject
* 2
* 3使DECLARE_DYNAMIC_CLASS(yourClassName); .cpp使IMPL_DYNAMIC_CLASS(yourClassName)
* 4
* .h中
* #include <QObject>
* #include "../common/reflect.h"
* class MyClass : public QObject
* {
* Q_OBJECT
* DECLARE_DYNCREATE(MyClass)
* }
*
* .cpp文件中
* IMPLEMENT_DYNCREATE(MyClass)
*/
#ifndef REFLECT_H
#define REFLECT_H
#include <QObject>
#include <QHash>
#include <QString>
typedef QObject * (*Constructor)();
class Reflect
{
public:
static int registerClass(const QString& className, Constructor constructor);
static QObject * createObject(const QString& className);
private:
static QHash<QString, Constructor>& constructors();
};
#define DECLARE_DYNCREATE(class_name) \
public: \
static QObject * create##class_name##Object();
#define IMPLEMENT_DYNCREATE(class_name) \
QObject * class_name::create##class_name##Object() \
{ \
return (QObject *)(new class_name()); \
} \
static int g_icreate##class_name##Object = Reflect::registerClass(#class_name, class_name::create##class_name##Object);
#endif //!REFLECT_H