在使用自定义类的时候如果遇到这个问题,可以在 main.cpp 函数中加入如下的注册方法。其中 YourClass 为我们的自定义类的名称。
qRegisterMetaType<YourClass>("YourClass");
使用示例:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlEngine>
#include <QQmlContext>
#include "src/TypeManager.h"
#include "src/TypeItem.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qRegisterMetaType<TypeItem>("TypeItem"); // 使用示例
TypeManager* typeManager = new TypeManager(&app);
engine.rootContext()->setContextProperty("typeManager", typeManager);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
网友评论