1、對於用戶,ListView是一個滾動區域,支持慣性滾動。(代理項delegates)
import QtQuick 2.0 Rectangle{ width: 80 height: 300 color: "white" ListView{ anchors.fill: parent anchors.margins: 20 clip:true model:100 delegate: numberDelegate spacing: 5 } Component{ id:numberDelegate Rectangle{ width: 40 height: 40 color: "lightGreen" Text{ anchors.centerIn: parent font.pixelSize: 10 text:index } } } }
Component只能包含一個頂層Item,而且在這個Item之外不能定義任何數據,除了id。 在頂層Item之內,則可以包含更多的子元素來協同工作,最終形成一個具有特定功能的組件。
Component通常用來給一個View提供圖形化組件,比如ListVIew::delegate屬性就需要一個Component來指定如何顯示列表的每一個項,又比如ButtonStyle::background屬性也需要一個Component來指定如何繪制Button的背景。
Component不是Item的派生類,而是從QQmlComponent繼承而來的,雖然它通過自己的頂層Item為其他的view提供可視化組件,但它本身是不可見元素。你可以這么理解:你定義的組件是一個新的類型,他必須被實例化以后才能顯示。而要實例化一個嵌入在QML文件中定義的Component,則可以通過Loader。
2、orientation(方向)
默認的鏈表視圖只提供了一個垂直方向的滾動條,但是有時我們也需要水平方向的
ListView{
.
.
.
orientation:ListView.Horizontal
}
鍵盤導航和高亮
當使用基於觸摸方式的鏈表視圖時,默認提供的視圖已經足夠使用。在使用鍵盤甚至僅僅通過方向鍵選擇一個元素的場景下,需要有標識當前選中元素的機制。在QML中,這被叫做高亮。
focus屬性設置為true,它設置鏈表視圖能夠獲得鍵盤焦點。
然后是highlight屬性,指出使用的高亮代理元素。
import QtQuick 2.0 Rectangle{ width: 240 height: 300 color: "white" ListView{ anchors.fill: parent anchors.margins: 20 clip:true model:100 // orientation: ListView.Horizontal delegate: numberDelegate spacing: 5 highlight: highlightComponent focus: true } Component{ id:highlightComponent Rectangle{ width: rect.width color: "lightGreen" } } Component{ id:numberDelegate Item{ id:rect width: 40 height: 40 // color: "lightGreen" Text{ anchors.centerIn: parent font.pixelSize: 10 text:index } } } }

添加動畫效果
Component{ id:highlightComponent // Rectangle{ // width: rect.width // color: "lightGreen" // } Item { width: ListView.view.width height: ListView.view.currentItem.height y: ListView.view.currentItem.y Behavior on y { SequentialAnimation { PropertyAnimation { target: highlightRectangle; property: "opacity"; to: 0; duration: 200 } NumberAnimation { duration: 1 } PropertyAnimation { target: highlightRectangle; property: "opacity"; to: 1; duration: 200 } } } Rectangle { id: highlightRectangle anchors.fill: parent color: "lightGreen" } } }
ListView與Component一般情況下需要配合使用