注意 在我们详细介绍前,我们先介绍⼀些相关的元素,红⾊(red),蓝⾊ (blue),绿⾊(green),⾼亮(lighter)与⿊暗(darker)⽅块,每⼀ 个组件都包含了⼀个48乘48的着⾊区域。下⾯是关于RedSquare(红⾊⽅ 块)的代码:
// RedSquare.qml
import QtQuick 2.0
Rectangle {
width: 48
height: 48
color: "#ea7025"
border.color: Qt.lighter(color)
}
Column
Column
(列)元素将它的⼦对象通过顶部对⻬的列⽅式进⾏排列。spacing
属性⽤来设置每个元素之间的间隔⼤⼩。
import QtQuick 2.0
DarkSquare {
id: root
width: 120
height: 240
Column {
id: column
anchors.centerIn: parent
spacing: 8
RedSquare { }
GreenSquare { width: 96 }
BlueSquare { }
}
}
Row
Row(⾏)元素将它的⼦对象从左到右,或者从右到左依次排列,排列⽅式 取决于layoutDirection
属性。spacing
属性⽤来设置每个元素之间的间隔⼤⼩。
// row.qml
import QtQuick 2.0
BrightSquare {
id: root
width: 400; height: 120
Row {
id: row
anchors.centerIn: parent
spacing: 20
BlueSquare { }
GreenSquare { }
RedSquare { }
}
}
Grid
Grid
(栅格)元素通过设置rows(⾏数)和columns(列数)将⼦对象排列 在⼀个栅格中。可以只限制⾏数或者列数。如果没有设置它们中的任意⼀ 个,栅格元素会⾃动计算⼦项⺫总数来获得配置,例如,设置rows(⾏数) 为3,添加了6个⼦项⺫到元素中,那么会⾃动计算columns(列数)为2。属 性flow(流)与layoutDirection
(布局⽅向)⽤来控制⼦元素的加⼊顺序。 spacing
属性⽤来控制所有元素之间的间隔。
import QtQuick 2.0
BrightSquare {
id: root
width: 160
height: 160
Grid {
id: grid
rows: 2
columns: 2
anchors.centerIn: parent
spacing: 8
RedSquare { }
RedSquare { }
RedSquare { }
RedSquare { }
}
}
Flow
通过flow(流)属性和layoutDirection
(布局 ⽅向)属性来控制流的⽅向。它能够从头到底的横向布局,也可以从左到右 或者从右到左进⾏布局。作为加⼊流中的⼦对象,它们在需要时可以被包装 成新的⾏或者列。为了让⼀个流可以⼯作,必须指定⼀个宽度或者⾼度,可 以通过属性直接设定,或者通过anchor
(锚定)布局设置。
import QtQuick 2.0
BrightSquare {
id: root
width: 160
height: 160
Flow {
anchors.fill: parent
anchors.margins: 20
spacing: 20
RedSquare { }
BlueSquare { }
GreenSquare { }
}
}
Repeater
通常Repeater
(重复元素)与定位器⼀起使⽤。它的⼯作⽅式就像for
循环与 迭代器的模式⼀样。在这个最简单的例⼦中,仅仅提供了⼀个循环的例⼦。
// repeater.qml
import QtQuick 2.0
DarkSquare {
id: root
width: 252
height: 252
property variant colorArray: ["#00bde3", "#67c111", "#ea7025"]
Grid{
anchors.fill: parent
anchors.margins: 8
spacing: 4
Repeater {
model: 16
Rectangle {
width: 56; height: 56
property int colorIndex: Math.floor(Math.random()*3)
color: root.colorArray[colorIndex]
border.color: Qt.lighter(color)
Text {
anchors.centerIn: parent
color: "#f0f0f0"
text: "Cell " + index
}
}
}
}
}