在QML的官方例子里面, 基本上都是一樣的Delegate, 也就是說不管數據怎樣, 樣式都是不變的.
如果我們想要根據不同的數據類型來顯示不同的UI該怎么辦? 這里有一個例子.
DataBank
ListModel { id: dataBank ListElement { value: "http://www.wondericons.com/dogs/myspace_dogs_icons_02.gif" type: "image" } ListElement { value: "Dummy text 1" type: "text" } ListElement { value: "http://www.wondericons.com/dogs/myspace_dogs_icons_08.gif" type: "image" } ListElement { value: "Dummy text 2" type: "text" } }
MultiDelegate
Item { id: multiDelegate height: 80 width: multiDelegate.ListView.view.width function bestDelegate(t) { if(t == "image") return imgDelegate; return txtDelegate; // t == "text" } Component { id: imgDelegate Image { id: img source: value fillMode: Image.PreserveAspectFit asynchronous: true } } Component { id: txtDelegate Text { id: txt text: value verticalAlignment: Text.AlignVCenter horizontalAlignment: Text.AlignHCenter } } Loader { id: itemDisplay anchors.fill: parent; anchors.topMargin: 2 anchors.bottomMargin: 2 sourceComponent: bestDelegate(type) } Rectangle { id: separator width: parent.width; height: 1; color: "#cccccc" anchors.bottom: parent.bottom } }
Main
Rectangle { ListView { id: dataView height: contentHeight anchors.fill: parent spacing: 2 model: DataBank{} delegate: MultiDelegate{} } }
重點就在JavaScript函數 bestDelegate(type); 和QML的Loader元素;
在ListView選擇delegate的時候會動態地根據數據類型來顯示不同的樣式;
<Refer to> http://cdumez.blogspot.com/2010/11/heterogeneous-list-model-in-qml.html