GridView(网格视图)
GridView的用法和ListView相似,都是继承自Flickable,但GridView是将项目排列成网络。
属性方面的话和ListView类似,相似的这里就不在列举。
1.基本的使用
ListModel {
id: nameModel
ListElement { name: "Alice"; team: "Crypto" }
ListElement { name: "Bob"; team: "Crypto" }
ListElement { name: "Jane"; team: "QA" }
ListElement { name: "Victor"; team: "QA" }
ListElement { name: "Wendy"; team: "Graphics" }
}
Component {
id: nameDelegate
Text {
text: name;
font.pixelSize: 24
anchors.leftMargin: 2
}
}
GridView{
anchors.fill:parent
model: nameModel
delegate: nameDelegate
}
2.网格视图的布局:
flow (流动)
GridView.FlowLeftToRight (default) 从左到右流动 |
GridView.FlowTopToBottom 从上到下流动 |
GridView{
anchors.fill:parent
model: nameModel
flow:GridView.FlowTopToBottom //设置为从上到下流动
delegate: nameDelegate
}
layoutDirection(控制水平布局方向)
Qt.LeftToRight(默认) | 项目将从左上角开始布局 |
Qt.rightToLeft | 项目将从右上角开始布局 |
使用从右上角开始布局:
GridView{
anchors.fill:parent
model: nameModel
layoutDirection: Qt.RightToLeft//从右上角开始布局
delegate: nameDelegate
}
verticalLayoutDirection(控制垂直布局方向)
GridView.TopToBottom (default) | 项目从视图顶部向下到视图底部进行布局 |
GridView.BottomToTop | 项目从视图底部到视图顶部进行布局 |
3.突出(高亮)的使用:
GridView{
anchors.fill:parent
model: nameModel
delegate: nameDelegate
highlight: Rectangle{color: "lightBlue"}
focus:true
}
4.移动函数的使用
moveCurrentIndexDown() | 在视图中将当前索引下移一项 |
moveCurrentIndexLeft() | 在视图中将当前索引向左移动一项 |
moveCurrentIndexRight() | 在视图中将当前索引右移一项 |
moveCurrentIndexUp() | 在视图中将当前索引上移一项 |
实现w、a、s、d、移动:
GridView{
id:grid1
anchors.fill:parent
model: nameModel
delegate: nameDelegate
highlight: Rectangle{color: "lightBlue"}
focus:true
Keys.onPressed: {
if(event.key===Qt.Key_W){
grid1.moveCurrentIndexUp()
}
else if(event.key===Qt.Key_A){
grid1.moveCurrentIndexLeft()
}
else if(event.key===Qt.Key_S){
grid1.moveCurrentIndexDown()
}
else if(event.key===Qt.Key_D){
grid1.moveCurrentIndexRight()
}
}
}
5.鼠标事件:
GridView{
id:grid1
anchors.fill:parent
model: nameModel
delegate: nameDelegate
highlight: Rectangle{color: "lightBlue"}
focus:true
MouseArea{
anchors.fill: parent
onPressed: {
grid1.currentIndex=grid1.indexAt(mouseX,mouseY)
}
}
}
6.设置单元格大小:
cellWidth | 单元格宽度 |
cellHeight: | 单元格高度 |
GridView{
id:grid1
anchors.fill:parent
model: nameModel
delegate: nameDelegate
highlight: Rectangle{color: "lightBlue"}
focus:true
cellWidth: 200
cellHeight: 200
}