QML中多样化的ListModel(MultiDelegate)

在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

 

posted @ 2013-06-22 12:49  jlins  阅读(7237)  评论(0编辑  收藏  举报