在我们设计我们的QML应用时,我们想通过一个方法在一个地方来改变我们的设置文件,从而来修改整个应用的外观或使得所有的使用同一个设置的变量值得到修改。比如我们可以设置BaseUrl="http://api.map.baidu.com/telematics/v3/weather?” 属性,我们可能有几个QML文件都需要使用这个属性,那么我们怎么没做呢?一种办法就是在每个模块中都定义同样的属性。另外一种办法就是利用Singleton来集中定义在一个文件中,从而被所有的模块所使用。这样的方法同样适合我们style我们的应用。我们在一个地方修改设置,但是在所有的模块中都使用。这类似于C/C++中定义一些常量,在不同的.cpp文件中使用一样。
为了能够实现我们上面所需要的功能,我们设计了如下的Settings.qml文件:
pragma Singleton
import QtQuick 2.0
QtObject {
    property int screenHeight: 960
    property int screenWidth: 640
    property string textSize: "x-large"
    property string textColor: "red"
}
singleton Settings 1.0 Settings.qml
import QtQuick 2.0
import Ubuntu.Components 1.1
// Needed for singletons QTBUG-34418
import "."
Tab {
    title: i18n.tr("Tab 1")
    Action {
        id: reloadAction
        text: "Reload"
        iconName: "reload"
        onTriggered: {
            console.log("reload is clicked")
        }
    }
    page: Page {
        Label {
            anchors.centerIn: parent
            text: i18n.tr("This is page one")
            color: Settings.textColor
            fontSize: Settings.textSize
        }
        tools: ToolbarItems {
            ToolbarButton {
                action: reloadAction
            }
        }
    }
}
import QtQuick 2.0
import Ubuntu.Components 1.1
// Needed for singletons QTBUG-34418
import "."
Tab {
    title: i18n.tr("Tab 2")
    page: Page {
        Label {
            anchors.centerIn: parent
            text: i18n.tr("This is page two")
            color: Settings.textColor
            fontSize: Settings.textSize
        }
    }
}
// Settings.qml
.pragma Singleton
 
QtObject {
 
property QtObject window: QtObject{
 property color background: "white";
 }
 
property QtObject border: QtObject{
 property QtObject width: QtObject{
 property int normal: 1;
 property int big: 3;
 }
 
property QtObject color: QtObject{
 property color normal: "gray";
 property color focus: "blue";
 property color disabled: "red";
 }
 }
}版权声明:本文为博主原创文章,未经博主允许不得转载。
QML Styling 及 Singleton 使用方法浅谈
原文:http://blog.csdn.net/ubuntutouch/article/details/46980635