qml中listview的嵌套(qt listview详细用法)

前言

有时,链表的数据需要分组。例如使用首字母来划分联系人,或者分类音乐。使用链表视图可以把平面列表按类别划分。

如何分组?

为了使用分组,section.property与section.criteria必须设置。section.property定义了哪些属性用于内容的划分。在这里,最重要的是知道每一组的元素必须连续,否则相同的属性名可能出现在几个不同的地方。

section.criteria能够被设置为ViewSection.FullString或者
ViewSection.FirstCharacter。默认下使用第一个值,能够被用于模型中有清晰的分组,例如音乐专辑。第二个是使用一个属性的首字母来分组,这说明任何属性都可以被使用。通常的例子是用于联系人名单中的姓。

当组被定义好后,每个子项能够使用绑定属性ListView.section,ListView.previousSection与ListView.nextSection来访问。使用这些属性,可以检测组的第一个与最后一个子项。

使用ListView的section.delegate属性可以给组指定代理组件。它能够创建段标题,并且可以在任意子项之前插入这个段代理。使用绑定属性section可以访问当前段的名称。

下面这个例子使用国际分类展示了分组的一些概念。国籍作为section.property,组代理组件(section.delegate)使用每个国家作为标题。在每个组中,spacemen模型中的名字使用spaceManDelegate组件来代理显示。

import QtQuick 2.3
import QtQuick.Window 2.2

Window {
id: root
visible: true
width: 480
height: 300
color: "white"

ListView {
anchors.fill: parent
anchors.margins: 20
clip: true
model: spaceMen
delegate: spaceManDelegate
section.property: "nation"
section.delegate: sectionDelegate
}

Component {
id: spaceManDelegate
Item {
width: 260
height: 20
Text {
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
anchors.leftMargin: 10
font.pixelSize: 12
text: name
}
}
}

Component {
id: sectionDelegate
Rectangle {
width: 260
height: 20
color: "lightBlue"
Text {
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
anchors.leftMargin: 10
font.pixelSize: 12
font.bold: true
text: section
}
}
}

ListModel {
id: spaceMen
ListElement { name: "小赵"; nation: "中国" }
ListElement { name: "小钱"; nation: "中国" }
ListElement { name: "小孙"; nation: "中国" }
ListElement { name: "小李"; nation: "中国" }
ListElement { name: "Amy"; nation: "美国" }
ListElement { name: "David"; nation: "美国" }
ListElement { name: "Kim"; nation: "美国" }
ListElement { name: "Helen"; nation: "俄罗斯" }
ListElement { name: "Kate"; nation: "俄罗斯" }
}
}

运行效果如下:

qml中listview的嵌套(qt listview详细用法)

如果同一组下的内容不联系,如下面的代码所示:

ListModel {
id: spaceMen
ListElement { name: "小赵"; nation: "中国" }
ListElement { name: "小钱"; nation: "中国" }
ListElement { name: "Amy"; nation: "美国" }
ListElement { name: "Kim"; nation: "美国" }
ListElement { name: "Helen"; nation: "俄罗斯" }
ListElement { name: "Kate"; nation: "俄罗斯" }
ListElement { name: "小孙"; nation: "中国" }
ListElement { name: "小李"; nation: "中国" }
ListElement { name: "David"; nation: "美国" }
}

即会出现多个相同的属性名,运行效果如下:

qml中listview的嵌套(qt listview详细用法)

(0)
小多多的头像小多多创始人

相关推荐

发表回复

登录后才能评论