QML使用C++的类
qmlobjectdefine.h
#ifndef QMLOBJECTDEFINE_H
#define QMLOBJECTDEFINE_H
#include <qobjectdefs.h>
#include <qqml.h>
#define QML_FUNCTION Q_INVOKABLE
#define QML_MEMBER_NAME(NAME) m_##NAME
#define QML_SIGNAL_NAME(NAME) NAME##Changed
#define QML_MEMBER_VARIABLE(TYPE, NAME) TYPE m_##NAME
#define QML_MEMBER_SIGNAL(NAME) void NAME##Changed()
#define QML_PROPERTY(TYPE, NAME) Q_PROPERTY(TYPE NAME MEMBER m_##NAME NOTIFY NAME##Changed)
#define QML_CREATE_PROPERTY(TYPE, NAME) QML_MEMBER_SIGNAL(NAME); public:QML_MEMBER_VARIABLE(TYPE, NAME); QML_PROPERTY(TYPE, NAME);
#define QML_REGISTER_TYPE(NAME, MAJOR, MINOR) qmlRegisterType<NAME>(#NAME, MAJOR, MINOR, #NAME);
#define QML_REGISTER_SINGLETON_TYPE(NAME, MAJOR, MINOR) qmlRegisterSingletonType<NAME>(#NAME, MAJOR, MINOR, #NAME, [](QQmlEngine *engine, QJSEngine *scriptEngine) -> QObject * { Q_UNUSED(engine) Q_UNUSED(scriptEngine) return new ObjectTester; })
#endif // QMLOBJECTDEFINE_H
c++的类注册到qml
#ifndef OBJECTTESTER_H
#define OBJECTTESTER_H
#include <QObject>
#include "qmlobjectdefine.h"
class ObjectTester : public QObject
{
Q_OBJECT
public: signals:
QML_CREATE_PROPERTY(QString, name)
public: signals:
QML_CREATE_PROPERTY(int, age)
public:
QML_FUNCTION QString output();
public:
explicit ObjectTester(QObject *parent = nullptr);
};
#endif // OBJECTTESTER_H
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QDebug>
#include <QFontDatabase>
#include <qmlobjectdefine.h>
#include <objecttester.h>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
#if 1
QMap<QString, int> objectMap;
objectMap["ObjectTester"] = QML_REGISTER_SINGLETON_TYPE(ObjectTester, 1, 0);
ObjectTester* instanceObjectTester = engine.singletonInstance<ObjectTester*>(objectMap["ObjectTester"]);
instanceObjectTester->m_name = "张三";
instanceObjectTester->m_age = 15;
#endif
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import ObjectTester 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log(ObjectTester.output())
console.log(ObjectTester.name)
console.log(ObjectTester.age)
}
}
标签:qml,NAME,ObjectTester,c++,QML,使用,include,TYPE,define
From: https://www.cnblogs.com/yuanhaoblog/p/18078692