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组件注册单例的方法