QML之GridView实现滑动的网格布局

最近在做关于滑动网格的需求,正好用到了GridView实现对应的功能。
在这里插入图片描述

1、GridView 关键属性

GridView相关的属性比较多,下面是一些关键的属性:

cellHeight: 表格中单个格子的高度
cellWeight: 表格中单个格子的宽度
currentIndex: 当前焦点所在的索引
delegate: 代理,即格子内的实现方式
layoutDirection: 所有格子的排列顺序
model: 表格的数据

2、GridView实现滑动表格

在这里插入图片描述

实现思路:

1、创建一个GridView,设置格子的大小
2、创建一个model(即数据库),一个delegate(格子内的显示形式)

实现代码:
main.qml

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    id:root
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Rectangle {
        anchors.fill:        parent
        anchors.margins:     10
        border.color:        "black"

        GridView {
            id:              grid
            anchors.fill:    parent
            cellWidth:       200
            cellHeight:      200
            anchors.margins: 20
            model:           ShowModel{}
            delegate:        ShowDelegate{}
            clip:            true  // 超出边界的进行裁剪,即不显示,默认为false
            boundsBehavior:  Flickable.StopAtBounds  // 滑动不超出父框的大小
        }
    }
}

ShowModel.qml

import QtQuick 2.0

ListModel {
    id: fruitModel
    ListElement {
        name:"apple"
        picSrc: "pic/apple.jpg"
        cost: 2
    }

    ListElement {
        name:"banana"
        picSrc: "pic/香蕉.jpg"
        cost: 2
    }

    ListElement {
        name:"orange"
        picSrc:"pic/橘子.jpg"
        cost: 2
    }

    ListElement {
        name:"pair"
        picSrc:"pic/梨.jpg"
        cost: 2
    }
    ListElement {
        name:"apple"
        picSrc: "pic/apple.jpg"
        cost: 2
    }

    ListElement {
        name:"banana"
        picSrc: "pic/香蕉.jpg"
        cost: 2
    }

    ListElement {
        name:"orange"
        picSrc:"pic/橘子.jpg"
        cost: 2
    }

    ListElement {
        name:"pair"
        picSrc:"pic/梨.jpg"
        cost: 2
    }
}

ShowDelegate.qml

import QtQuick 2.0

Rectangle {
    width: grid.cellWidth
    height: grid.cellHeight
    anchors.margins: 10
    radius: 10
    border.color: "black"
    Image{
        anchors.horizontalCenter:   parent.horizontalCenter
        anchors.verticalCenter:     parent.verticalCenter
        source:                     model.picSrc
        sourceSize.width:           parent.width * 0.90
        sourceSize.height:          parent.height * 0.90
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            console.log(parent.width, parent.height)
        }
    }
}
  • 9
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值