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官方文档才知道的。