Qt 5.12--Qt qml 单例模式

1 简介

保证仅有一个实例,并提供一个访问它的全局访问点。

2 步骤

2.1 将一个QML组件声明为单例

Common.qml

pragma Singleton
import QtQuick 2.12
QtObject {
    readonly property color btnColor: 'lightgray';
    readonly property int textSize: 20
}

2.2 注册组件

方法一:在C++中注册组件

qmlRegisterSingletonType( QUrl("qrc:/Common.qml"), "CommonST ", 1, 0, "Common " );

方法二:使用qmldir文件
将名为qmldir的文件添加到Common.qml文件所在的目录,并添加进工程。
qmldir的文件内容如下:

singleton Common Common.qml

在这里插入图片描述

2.3 TestSingleton.qml

通过qmldir方式创建的单例,使用如下

import QtQuick 2.12
import "."  // 单例模式必须显式的调用qmldir文件
Rectangle {
    width: 500
    height: 500
    color: Common .btnColor;
    Text{
        text: 'hello world'
        font.pixelSize: Common .textSize  // 调用单例对象的属性
        anchors.centerIn: parent
    }
}

通过qmlRegisterSingletonType方式创建的单例,使用如下

import QtQuick 2.12
import ca.mystyle 1.0

import "."  // 单例模式必须显式的调用qmldir文件
Rectangle {
    width: 500
    height: 500
    color: Common .btnColor;
    Text{
        text: 'hello world'
        font.pixelSize: CommonST.textSize  // 调用单例对象的属性
        anchors.centerIn: parent
    }
}

参考

1、Qt qml 单例模式
2、QML Styling 及 Singleton 使用方法浅谈
3、QML组件单例模式
4、QML组件注册单例的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

worthsen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值