ListView的用法


ListElement定义了单元属性,这些属性是ListModel和delegate通信的基础


ListModel动态添加元素时,需要给定的ListElement中定义的属性。


delegate中显示元素也是引用ListElement中的属性。



ListView的delegate有两种方式。


第一种方式:直接定义delegate。

importQtQuick2.5

Rectangle{
id:qq
width:400
height:400
visible:true
color:"red"

ListModel{
id:w3
ListElement{colorr:"#FFA120";name:"nafefe"}
ListElement{colorr:"#A24345";name:"eeeee"}
ListElement{colorr:"#001123";name:"ttttttttt"}
}

ListView{
id:q1
width:parent.width;
height:parent.height
model:w3

delegate:Item{
id:w4
width:30
height:30
Rectangle{
id:w1
anchors.fill:w4
color:colorr
}
Text{
id:w2
text:name
anchors{left:w4.right}
anchors.verticalCenter:w4.verticalCenter
}
}
}
}

运行结果如下:


第二种方式:
将delegae定义成组件,在ListView中加用其id。
importQtQuick2.5

Rectangle{
id:qq
width:400
height:400
visible:true
color:"red"

ListModel{
id:w3
ListElement{colorr:"#FFA120";name:"nafefe"}
ListElement{colorr:"#A24345";name:"eeeee"}
ListElement{colorr:"#001123";name:"ttttttttt"}
}

ListView{
id:q1
width:parent.width;
height:parent.height
model:w3

delegate:ContactModel{}
}
}
在另一个文件中进行组件的定义,给文件命名为ContactModel.qml
//组件定义,在原有Item基础上加在Component {id:eew}
importQtQuick2.0
Component{
id:eew
Item{
id:w4
width:30
height:30
Rectangle{
id:w1
anchors.fill:w4
color:colorr
}
Text{
id:w2
text:name
anchors{left:w4.right}
anchors.verticalCenter:w4.verticalCenter
}
}
}

效果如图所示:



总结:model:放置的是ListModel的id,用于读取其中的参数数据

relegate:放置组件id或者文件名引用



在组件中添加鼠标点击事件,需要使用index


importQtQuick2.0

Component{

id:eew

Item{

id:w4

width:30

height:30

Rectangle{

id:w1

anchors.fill:w4

color:colorr

}

Text{

id:w2

text:name

anchors{left:w4.right}

anchors.verticalCenter:w4.verticalCenter

}

MouseArea{

anchors.fill:w1

onClicked:{

q1.currentIndex=index;

varhh=q1.currentIndex;

console.log(hh);

}

}

}

}
 
relegate:放置组件id或者文件名引用

现在还不清楚index怎么就获取到了鼠标点击的是rectangle块,但是鼠标的点击事件功能已经实现了。

参考文章:



 

 http://blog.163.com/wslngcjsdxdr%40126/blog/static/16219623020147133550574/



上面获取了鼠标点击Rectangle的点击序列,便可以进行界面切换了,在上层文件中声明变量,然后在获取到的序列中复制,在通过visible属性进行判断显示即可,代码如下: