除了动画效果外,还有一个实用的功能就是按条件分组。如同手机里通讯录一般
section,就是实现分组的主角,简略讲讲这个主角的本领
section.property 表明了分组的依据,比如section.property: "cost"
section.criteria 指定了section,property的判断条件,通常有ViewSection.FullString和ViewSection.FirstCharacter两种,全串匹配和首字母匹配。匹配时不区分大小写
section.delegate 通过设置一个component,来显示每个section
还有很多section的属性,具体的可查帮助文档。不过有一点需要注意:listview的分组不会自动排序,也就是说,如果apple和huawei的手机交替出现时,那么listview则可能会显示多个 相同的section.
下面是个具体的实例
import QtQuick 2.2import QtQuick.Controls 1.1import QtQuick.Layouts 1.1Rectangle { width: 360 height: 400 color: "#EEEEEE" Component{ id: phoneModel ListModel{ ListElement{ name: "iphone 5" cost: "4900" manufacture: "Apple" } ListElement{ name: "iphone 3gs" cost: "1000" manufacture: "Apple" } ListElement{ name: "iphone 4" cost: "1800" manufacture: "Apple" } ListElement{ name: "iphone 4s" cost: "2300" manufacture: "Apple" } ListElement{ name: "B199" cost: "1590" manufacture: "HuaWei" } ListElement{ name: "c88160" cost: "590" manufacture: "HuaWei" } ListElement{ name: "galaxy s5" cost: "2300" manufacture: "sumsung" } ListElement{ name: "galaxy s7" cost: "4900" manufacture: "sumsung" } ListElement{ name: "galaxy s4" cost: "1200" manufacture: "sumsung" } ListElement{ name: "MI5" cost: "2300" manufacture: "XiaoMi" } } }// phoneModel is end Component{ id: phoneDelegate Item { id: wrapper width: parent.width height: 30 ListView.onAdd: console.log("count:", ListView.view.count) MouseArea{ anchors.fill: parent onClicked: wrapper.ListView.view.currentIndex = index } RowLayout{ anchors.left: parent.left anchors.verticalCenter: parent.verticalCenter spacing: 8 Text{ id: coll text: name color: wrapper.ListView.isCurrentItem ? "red" : "black" font.pixelSize: wrapper.ListView.isCurrentItem ? 22 : 18 Layout.preferredWidth: 120 } Text{ text: cost color: wrapper.ListView.isCurrentItem ? "red" : "black" font.pixelSize: wrapper.ListView.isCurrentItem ? 22 : 18 Layout.preferredWidth: 80 } Text{ text: manufacture color: wrapper.ListView.isCurrentItem ? "red" : "black" font.pixelSize: wrapper.ListView.isCurrentItem ? 22 : 18 Layout.fillWidth: true } } } }//phoneDelegate is end Component{ id: sectionHeader Rectangle{ width: parent.width height: childrenRect.height color: "lightsteelblue" Text{ text: section font.bold: true font.pointSize: 20 } } }//sectionHeader is end ListView{ id: listView anchors.fill: parent delegate: phoneDelegate model: phoneModel.createObject(listView) focus: true highlight: Rectangle{ color: "lightblue" } /* 特别注意的是,listview的分组不会引起listview自动按分组来处理Item的顺序。如果listView的Model * 内的数据没有按分组顺序编排,比如说samsung和apple的手机在model内交替出现,那么listview则可能会 * 显示多个相同的section */ section.property: "manufacture" section.criteria: ViewSection.FullString section.delegate: sectionHeader }}