Qt通过QMetaObject创建实例

myclass.h

#ifndef MYCLASS_H
#define MYCLASS_H

#include 

class MyClass:public QObject
{
    Q_OBJECT
public:
    Q_INVOKABLE explicit MyClass(QObject *parent = nullptr);
    Q_INVOKABLE void myMethod();
};

#endif // MYCLASS_H

myclass.cpp

#include "myclass.h"

#include 

MyClass::MyClass(QObject *parent) :QObject(parent)
{

}

void MyClass::myMethod()
{
    qDebug() << "Hello, world!";
}

main.cpp

#include 
#include 
#include 
#include 
#include 
#include 
#include "myclass.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    const QMetaObject metaObject = MyClass::staticMetaObject;
    QObject *myObject = metaObject.newInstance(Q_ARG(QObject*, nullptr));
//    QMetaObject::invokeMethod(myObject, "myMethod");

    qDebug()<<"hello world";
    qDebug()<<myObject;
    qDebug()<<"hello world";
    QMetaObject::invokeMethod(myObject, "myMethod");
    return a.exec();
}

重点在构造函数声明时**Q_INVOKABLE和 explicit MyClass(QObject parent = nullptr) 以及实现时MyClass::MyClass(QObject parent) :QObject(parent) 都必不可少,要不然返回的myObject就为nullptr。看了百度上的好多回答,都是错的,后来也是看Qt官方文档才知道的。
Qt通过QMetaObject创建实例_第1张图片

你可能感兴趣的:(Qt,qt,dubbo,开发语言)