zoukankan      html  css  js  c++  java
  • 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
       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
         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

  • 相关阅读:
    前端 network
    C语言的安装及使用
    c语言
    mongodb
    大型网站--负载均衡架构
    双机热备ROSE HA工作原理
    Linux vmstat命令实战详解
    管理员必备的20个Linux系统监控工具
    linux top命令详解
    linux命令TOP参数load average详解[转]
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3149666.html
Copyright © 2011-2022 走看看