合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
[TOC] ## 元对象实现工厂 **场景** 头文件都没有只知道类的名字,在这种情况下需要将对象实例化出来,同时还要调用类中的方法。 <details> <summary> person.h</summary> ``` #ifndef PERSON_H #define PERSON_H #include <QObject> #include <QDebug> class Person : public QObject { Q_OBJECT public: Q_INVOKABLE explicit Person(QObject *parent = nullptr); // 元对象调用的函数必须卸载 slots 中 public slots: void show(){ qDebug()<<__FUNCTION__<<metaObject()->className(); } QString echo(QString hello){ return QString("word %1").arg(hello); } }; #endif // PERSON_H ``` </details> <br /> <details> <summary> student.h</summary> ``` #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 ``` </details> <br /> <details> <summary> createperson.h</summary> ``` #ifndef CREATEPERSON_H #define CREATEPERSON_H #include <QHash> #include <QObject> #include <QString> #include "student.h" class CreatePerson { public: CreatePerson(); QObject* newPerson(QString name); private: QHash<QString,const QMetaObject*> m_members; }; #endif // CREATEPERSON_H ``` </details> <br /> <details> <summary> createperson.cpp</summary> ``` #include "createperson.h" #include <QDebug> 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" <<name; return nullptr; } return m_members[name]->newInstance(); } ``` </details> <br /> 调用 ``` 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()<<result; ``` > 需要是QObject子类,同时需要声明Q\_OBJECT,这样才能享受到元对象系统带来的福利。 > 元对象调用的函数必须在 slots 中声明