Qt之自定义属性Q_PROPERTY专题(3)应用案例QML

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;
    }
}

运行后:

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值