想用GridView实现携程商城那样的布局。
在这里介绍一下方法
ScrollView{
// z:1
// anchors.horizontalCenter: parent.horizontalCenter
anchors.top: rect1.bottom
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
anchors.left: parent.left
anchors.right: parent.right
GridView {
anchors.fill: parent
// anchors.margins: 20
// anchors.bottomMargin: 80
clip: true
model: ListModel {
id: theModel
ListElement {
eachname: "hahaha"
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"//加载图片资源
}
ListElement {
eachname: "lalala"
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
ListElement {
eachname: 2
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
ListElement {
eachname: 3
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
ListElement {
eachname: 4
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
ListElement {
eachname: 5
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
ListElement {
eachname: 6
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
ListElement {
eachname: 7
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
ListElement {
eachname: 8
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
ListElement {
eachname: 9
price:"¥60"
eachimage:"qrc:/new/prefix1/Image/xxx.jpg"
}
}
cellWidth: parent.width/2
cellHeight: 410
delegate: numberDelegate
}
Component {
id: numberDelegate
Rectangle {
id: wrapper
width: parent.width/2-10
height: 400
color: "lightGreen"
border.color: "black"
border.width: 1
Rectangle{ //使图片边角有圆弧
id:maskrect
radius: 10
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: parent.bottom
anchors.bottomMargin: 40
Image {
id:theimage
anchors.fill: parent
source: eachimage
visible: false
}
Rectangle{
id:themask
anchors.fill: parent
radius: 10
visible: false
}
OpacityMask{
source: theimage
maskSource: themask
anchors.fill: theimage
visible: true
}
}
radius: 10
Text {
id:landscape_name
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
font.pixelSize: 15
text: eachname
}
Text {
id:theprice
anchors.top: landscape_name.bottom
anchors.topMargin: 5
anchors.horizontalCenter: parent.horizontalCenter
text: price
font.pixelSize: 10
}
}
}
}
Component.onCompleted: {
theModel.append({"eachname":"123456","eachimage":"qrc:/new/prefix1/Image/obama2.jpg", "price":"¥60"})
}//添加元素
代码中较为关键的就是这两句话
cellWidth: parent.width/2
cellHeight: 410
这两句话是设置网格中每个单元格的宽和高,在这里我们要设置只有两列,所以我们让单元格的宽度为窗口的一半也就是cellWidth: parent.width/2然后还要注意的一个地方就是在GridView的代理中每个长方形的宽度和高度要比网格中的单元格小一些,这样GridView在自动排列时才能排列出想要的只有两列的效果
width: parent.width/2-10
height: 400
在设置GridView每个长方形的代码中的OpacityMask部分是用来实现图片也有圆形弧度的效果,大家也可以参考一下。