yhkylin-backup-tools/common/reflect.cpp

50 lines
1.4 KiB
C++
Raw Normal View History

2021-08-06 10:20:03 +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)
*/
#include "reflect.h"
int Reflect::registerClass(const QString& className, Constructor constructor)
{
QHash<QString, Constructor>& instances = constructors();
instances.insert(className, constructor);
return instances.size();
}
QObject * Reflect::createObject(const QString& className)
{
QHash<QString, Constructor>& instances = constructors();
if (instances.contains(className)) {
Constructor constructor = instances[className];
if (constructor != nullptr) {
return (*constructor)();
}
}
return nullptr;
}
QHash<QString, Constructor>& Reflect::constructors()
{
static QHash<QString, Constructor> _instances;
return _instances;
}