一、ListView的基本使用
ListVIEW显示内置QML类型(如ListModel)创建的模型数据,或者C++中自定义的模型类,这些模型类继承自QAbstractItemModel或QAbstractListModel。ListView继承了Flickable。
ListView有一个模型(model),用来定义要显示的数据,还有一个委托(delegate),用来定义如何显示数据。ListView的item是水平或垂直布局的。通过orientation指定
Window {
visible: true
id:root
width: 640
height: 480
ListView {
anchors.fill: parent
spacing: 5
model:20
delegate:box
}
Component {
id:box
Box {
text:index
height: 40
width: 150
}
}
}
如果想改变listview的排列方向,可以使用orientation属性,将其置为orientation:ListView.Horizontal
orientation:ListView.Horizontal
二、ListView的高亮显示
如果想让ListView中的数据有高亮效果,可以使用highlight属性,和delegate类似
Window {
visible: true
id:root
width: 320
height: 240
ListView {
anchors.fill: parent
spacing: 5
model:100
delegate:box
highlight: hl
focus: true
}
Component {
id:hl
Box {
z:10
opacity:0.5
width: ListView.view.width
color: "green"
}
}
Component {
id:box
Box {
z:0
height: 40
width: ListView.view.width
text:index
}
}
}
上述代码中通过ListView.view.width使得BOX和highlight和窗口同宽,通过Z属性设置box和highlight的层级关系,以及通过opacity设置highlight的透明度
三、ListView的header和footer(页眉页脚)
可以通过ListView的footer和header设置页眉页脚,只需要添加如下代码
Window {
//...
ListView {
//...
footer: fid
header: hid
}
Component {
id:hid
Box {
width: ListView.view.width
height: ListView.view.currentItem.height
color: "yellow"
text: "header"
}
}
Component {
id:fid
Box {
width: ListView.view.width
height: ListView.view.currentItem.height
color: "yellow"
text: "footer"
}
}
//...
}
四、GridView
GridView也是QML内置的组件类型,和ListView类似。
GridView有一个model和一个delegate,model定义要显示的数据,delegate定义应该如何显示数据。
GridView中的Grid是二维分布的。GridView继承自flickable。
和ListView都是类似的
参考
《qml book》
作者水平有限,如有错误,欢迎指出