Qt中类的Q_PROPERTY属性是给脚本和元对象系统用的,比如QtScript,QML,或者QObject::property/setProperty……,主要就是用来进行属性封装,在具体的脚本,库,qml开发中必须使用。
在QML中访问C++,通过C++类暴露属性来使用,接上面实例如下:
1、新建Qt Quick工程:qt PROPERTY
2、新建C++类TestProperty,公有继承于QObject
3、为TestProperty类设置上述属性title
Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged);
4、属性读写函数声明与实现
TestProperty.h
#ifndef TESTPROPERTY_H
#define TESTPROPERTY_H
#include <QObject>
class TestProperty : public QObject
{
Q_OBJECT
public:
explicit TestProperty(QObject *parent = nullptr);
Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged);
QString title();
void setTitle(QString strTitle);
signals:
void titleChanged();
public slots:
private:
QString m_title;
};
#endif // TESTPROPERTY_H
TestProperty.cpp
#include "TestProperty.h"
TestProperty::TestProperty(QObject *parent) : QObject(parent)
{
}
QString TestProperty::title()
{
return m_title;
}
void TestProperty::setTitle(QString strTitle)
{
m_title = strTitle;
emit titleChanged();
}
5、在main函数中注册这个类,导出到qml中
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <qglobal.h>
#include "TestProperty.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterType<TestProperty>("TestProperty", 1, 0, "TestProperty");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
6、在qml中调用title属性
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import TestProperty 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello Qt")
TestProperty{
id: testProperty
title: qsTr("Hello World")
}
Component.onCompleted: {
title = testProperty.title;
}
}
运行后: