
前言
今天我们来看看如何向视图中插入一个页眉(header)和一个页脚(footer)元素。对于一个水平链表视图,不会存在页眉或页脚,但是也有开始和结尾处,这取决于layoutDirection的设置。
页眉和页脚
下面这个例子展示了如何使用一个页眉和页脚来突出链表的开始与结尾。这些特殊的链表元素也有其它的作用,例如,它们能够保持链表中的按键加载更多的内容。
import QtQuick 2.3import QtQuick.Window 2.2Window { id: root visible: true width: 640 height: 480 color: "white" ListView { anchors.fill: parent anchors.margins: 20 clip: true model: 4 delegate: numberDelegate spacing: 5 header: headerComponent footer: footerComponent } Component { id: headerComponent Rectangle { width: 100 height: 40 color: "yellow" } } Component { id: footerComponent Rectangle { width: 100 height: 40 color: "red" } } Component { id: numberDelegate Rectangle { width: 100 height: 100 color: "lightGreen" Text { anchors.centerIn: parent font.pixelSize: 10 text: index } } }}
运行效果如下:

注意,页眉与页脚代理元素不遵循链表视图的spacing属性,它们被直接放在相邻的链表元素之上或之下。这意味着页眉与页脚的间隔必须通过页眉与页脚元素自己设置。
GridView(网格视图)
使用GridView与ListView的方式非常类似。真正不同的地方是GridView使用了一个二维数组来存放元素,而ListView是使用线性链表来存放元素。
与ListView比较,GridView不依赖与元素间隔和大小来配置元素。它使用cellWidth与cellHeight属性来控制数组内的二维元素的内容。每个元素从左上角开始依次放入单元格。
import QtQuick 2.3import QtQuick.Window 2.2Window { id: root visible: true width: 240 height: 300 color: "white" GridView { anchors.fill: parent anchors.margins: 20 clip: true model: 100 cellWidth: 45 cellHeight: 45 delegate: numberDelegate } Component { id: numberDelegate Rectangle { width: 40 height: 40 color: "lightGreen" Text { anchors.centerIn: parent font.pixelSize: 10 text: index } } }}
运行效果如下:

一个GridView也包含了页脚与页眉,也可以使用高亮代理并且支持捕捉模式的多种反弹行为。也可以使用不同的方向与定向来定位。
定向使用flow属性来控制。它可以被设置为GridView.LeftToRight或者GridView.TopToBottom。模型的值从左往右向网格中填充,行添加是从上往下。视图使用一个垂直方向的滚动条。后面添加的元素也是由上到下,由左到右。
此外还有flow属性和layoutDirection属性,能够适配网格从左到右或者从右到左。