[翻译] Qml 样式
QML 提供了几种机制来设置 UI 的样式。以下是三种常用的方法:
方法1:自定义组件
QML支持定义自己的自定义组件,下面,我们创建一个可以随时在UI中改变标题的自定义的 TitleText
组件,如果我们要改变我们的UI的所有标题的外观,我们只需编辑 TitleText.qml
,然后所做的更改将应用到所有引用它的地方。
// TitleText.qml
Text {
horizontalAlignment: Text.AlignHCenter
font.pixelSize: 50
color: "green"
}
// in use
TitleText {
text: "Title 1"
}
方法2:Style Singleton
在这种方法中,我们定义一个包含定义的样式属性的Style QML singleton对象,作为一个QML singletons,通用的实例可以从引用该目录的任何地方访问。需要注意的是QML singletons需要一个包含singleton关键字在Style类型定义之前的qmldir文件(比较绕口);它们不能像其他类型那样被隐式包含。当使用QRC资源是Style.qml和qmldir文件必须包含在.qrc资源文件中。
// Style.qml
pragma Singleton
import QtQuick 2.0
QtObject {
property int textSize: 20
property color textColor: "green"
}
// qmldir
singleton Style Style.qml
// in use
import QtQuick 2.0
import "." // QTBUG-34418, singletons require explicit import to load qmldir file
Text {
font.pixelSize: Style.textSize
color: Style.textColor
text: "Hello World"
}
方法3:混合(Style Singleton + Custom Component)
在这种方法中,假定我们有一个Style singleton被自定义组件引用。
// Style.qml
import QtQuick 2.0
pragma Singleton
QtObject {
property int titleAlignment: Text.AlignHCenter
property int titleFontSize: 50
property color titleColor: "green"
}
// TitleText.qml
import QtQuick 2.0
import "." // QTBUG-34418, singletons require explicit import to load qmldir file
Text {
horizontalAlignment: Style.titleAlignment
font.pixelSize: Style.titleFontSize
color: Style.titleColor
}
// in use
TitleText {
text: "Title 1"
}
嵌套QtObjects
如果您需要嵌套QtObject访问更多定义的属性(例如border.width.normal),你可以像下面那样做:
// Style.qml
import QtQml 2.2
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