如何在QML中使用GridView将网格按4个一组排列?
QML实现GridView网格项4个一组的布局
要实现GridView中网格项按4个一组排列、组间带间隔的效果,有两种实用方案:
方案一:数据分组后渲染
先将原始数据处理为每4个项一组的结构,再用GridView渲染每个组,组间间距通过GridView的spacing控制,组内项用Row紧凑排列。
import QtQuick 2.15 import QtQuick.Controls 2.15 Rectangle { width: 600 height: 200 color: "#f0f0f0" // 原始数据 ListModel { id: rawData ListElement { text: "c1" } ListElement { text: "c2" } ListElement { text: "c3" } ListElement { text: "c4" } ListElement { text: "c5" } ListElement { text: "c6" } ListElement { text: "c7" } ListElement { text: "c8" } ListElement { text: "c9" } ListElement { text: "c10" } ListElement { text: "c11" } ListElement { text: "c12" } } // 构建分组模型:每4个项为一组 ListModel { id: groupedModel Component.onCompleted: { let currentGroup = []; for (let i = 0; i < rawData.count; i++) { currentGroup.push(rawData.get(i).text); // 每4个一组,或到最后一项时收尾 if ((i + 1) % 4 === 0 || i === rawData.count - 1) { groupedModel.append({ items: currentGroup }); currentGroup = []; } } } } GridView { anchors.fill: parent model: groupedModel // 根据容器宽度自动计算一行可容纳的组数 columnCount: Math.floor(parent.width / (4 * 40 + 20)) spacing: 20 // 组与组之间的间距 delegate: Row { spacing: 0 // 组内项无间距,紧凑排列 Repeater { model: items Rectangle { width: 40 height: 40 color: "#2196F3" Text { anchors.centerIn: parent text: modelData color: "white" } } } } } }
这种方案逻辑清晰,方便给组添加整体样式(比如边框、背景),适合需要对组进行统一操作的场景。
方案二:基于索引的间距控制
无需修改原始数据,通过判断项的索引,给每组的第一个项(非第一组)添加左侧间距,模拟组间间隔。
import QtQuick 2.15 import QtQuick.Controls 2.15 Rectangle { width: 600 height: 200 color: "#f0f0f0" ListModel { id: rawData ListElement { text: "c1" } ListElement { text: "c2" } ListElement { text: "c3" } ListElement { text: "c4" } ListElement { text: "c5" } ListElement { text: "c6" } ListElement { text: "c7" } ListElement { text: "c8" } ListElement { text: "c9" } ListElement { text: "c10" } ListElement { text: "c11" } ListElement { text: "c12" } } GridView { anchors.fill: parent model: rawData columnCount: 4 // 每组固定4列 cellWidth: 40 cellHeight: 40 spacing: 0 // 项基础间距设为0 delegate: Rectangle { width: 40 height: 40 color: "#2196F3" // 非第一组的第一个项,添加左侧间距 leftPadding: (index % 4 === 0 && index !== 0) ? 20 : 0 Text { anchors.centerIn: parent text: model.text color: "white" } } } }
这种方案实现简单,无需预处理数据,适合仅需添加组间间距的场景。
内容的提问来源于stack exchange,提问作者3088 K
相关产品推荐
相关产品推荐

