Q_OBJECT宏定义定义了QObject的子类的元信息类对象,但是QObject好像没有注册所有子类的信息,那么在QT中该如何实现根据类名动态创建QObject子类的对象呢?
------解决方案--------------------
让MyObject继承自QObject
MyObject::staticMetaObject.newInstance()
构造函数前需加上Q_INVOKABLE
------解决方案--------------------
其实可以不用 Q_INVOKABLE
首先 有一个基类 可以使用 QObject, 这里使用 Parser
- C/C++ code
class Parser {public: virtual void parse() = 0; virtual ~Parser() {};};
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
- C/C++ code
#include <QApplication>#include <QMetaMethod>#include <iostream>using namespace std;class Test:public QObject{ Q_OBJECTpublic: Q_INVOKABLE Test(); Q_INVOKABLE void print();};Test::Test(){ cout<<"Test::Test()"<<endl;}void Test::print(){ cout<<"sss\n"<<endl;}#include "test.moc"int main(int argc,char* argv[]){ QApplication app(argc,argv); QMetaObject metaObject = Test::staticMetaObject; Test* object = (Test*)metaObject.newInstance(); object->print(); return app.exec();}