除了動畫效果外,還有一個實用的功能就是按條件分組。如同手機里通訊錄一般
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.2 import QtQuick.Controls 1.1 import QtQuick.Layouts 1.1 Rectangle { 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 } }