qml实现ListView中多个代理

qml中的ListView官方的例子里代理只能代理(delegate)一种组件,但很多时候我们的布局需要多种组件,则需要ListView代理多种组件。
这里的方法主要是用了一个博主的博客链接,这里我们需要将ListModuel与delegate分开成两个qml文件,然后在第三个qml文件用ListView去调用他们。

// ListModuel部分,注意是写在第一个qml文件中,Myitem.qml
ListModel {
     id: dataBank

     ListElement {
         value: "qrc:/new/prefix1/Image/obama2.jpg"
         type: "image"
     }
     ListElement {
         value: "Dummy text 1"
         type: "text"
     }
     ListElement {
         value: "qrc:/new/prefix1/Image/obama2.jpg"
         type: "image"
     }
     ListElement {
         value: "Dummy text 2"
         type: "text"
     }
 }
// delegate部分,注意是写在第二个qml文件中,Test2.qml
Item {
 id: multiDelegate
 height: {
     if(type==="image"){
         300
     }
     else{
         100
     }
 } //实现不同代理有不同高度的Item

//  width: multiDelegate.ListView.view.width-20
 anchors.left: parent.left
 anchors.right: parent.right
 anchors.leftMargin: 10
 anchors.rightMargin: 10
 function bestDelegate(t) {
   if(t === "image")
     return imgDelegate;
   return txtDelegate; // t == "text"
 }

 Component {
   id: imgDelegate
   Rectangle{
//        width: parent.width
//        height: 100
       radius: 10
       color: "green"
       Image {
         id: img
         source: value
         fillMode: Image.PreserveAspectFit
         asynchronous: true
         anchors.fill: parent
       }
   }
 }
 Component {
   id: txtDelegate
   Rectangle{
//         width: parent.width
//         height: 300
        radius: 10
        color: "red"
        Text {
          id: txt
          text: value
          verticalAlignment: Text.AlignVCenter
          horizontalAlignment: Text.AlignHCenter
          anchors.centerIn: parent
        }
   }
 }
 Loader {
   id: itemDisplay
   anchors.fill: parent;
   anchors.topMargin: 2
   anchors.bottomMargin: 2
   sourceComponent: bestDelegate(type)
 }
}
// 最后第三个文件中ListView调用他们
  ListView {
          id: dataView
          height: contentHeight
          anchors.fill: parent
          spacing: 20
          model: Myitem{}
          delegate: Test2{}
        }
        WebView{
            id: webVie1;
            anchors.fill: parent;
            url: "xxxx"
        }

看代码就知道主要是先在ListModuel设置type,然后自定义一个函数通过不同的参数用Loader加载不同的组件。这里我还在Item的height属性上加了一个判断,让不同的type组件有不同的高度。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值