工厂类
最后更新于:2022-04-02 02:15:44
[TOC]
## 元对象实现工厂
**场景**
头文件都没有只知道类的名字,在这种情况下需要将对象实例化出来,同时还要调用类中的方法。
#include
class Person : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE explicit Person(QObject *parent = nullptr);
// 元对象调用的函数必须卸载 slots 中
public slots:
void show(){
qDebug()<<__FUNCTION__<className();
}
QString echo(QString hello){
return QString("word %1").arg(hello);
}
};
#endif // PERSON_H
```
#include
#include
#include "student.h"
class CreatePerson
{
public:
CreatePerson();
QObject* newPerson(QString name);
private:
QHash m_members;
};
#endif // CREATEPERSON_H
```
CreatePerson::CreatePerson()
{
m_members["student"]=&Student::staticMetaObject;
//add m_members["teacher"] ...
}
QObject *CreatePerson::newPerson(QString name)
{
if(!m_members.contains(name)){
qDebug()<<"your class name is not found" <newInstance();
}
```
调用 ``` CreatePerson person; QObject *student = person.newPerson("student"); QMetaObject::invokeMethod(student,"show"); // 调用有参数和返回值的 QString result; QMetaObject::invokeMethod(student,"echo",Qt::AutoConnection, Q_RETURN_ARG(QString,result), Q_ARG(QString,"hello")); qDebug()< 需要是QObject子类,同时需要声明Q\_OBJECT,这样才能享受到元对象系统带来的福利。
> 元对象调用的函数必须在 slots 中声明
';
person.h
``` #ifndef PERSON_H #define PERSON_H #includestudent.h
``` #ifndef STUDENT_H #define STUDENT_H #include "person.h" class Student : public Person { Q_OBJECT public: Q_INVOKABLE explicit Student(QObject* parent=nullptr); }; #endif // STUDENT_H ```createperson.h
``` #ifndef CREATEPERSON_H #define CREATEPERSON_H #includecreateperson.cpp
``` #include "createperson.h" #include调用 ``` CreatePerson person; QObject *student = person.newPerson("student"); QMetaObject::invokeMethod(student,"show"); // 调用有参数和返回值的 QString result; QMetaObject::invokeMethod(student,"echo",Qt::AutoConnection, Q_RETURN_ARG(QString,result), Q_ARG(QString,"hello")); qDebug()<