QML实现双列滚动布局:4行2列展示,剩余内容可滚动
QML实现4行2列带滚动的ListModel布局方案
你需要的布局可以通过GridView + ScrollView组合实现,既能固定2列、4行的可见区域,又支持内容超出时滚动浏览。以下是修改后的完整代码:
Window { width: 300 height: 480 visible: true title: qsTr("Hello World") Rectangle { width: 300 height: 480 ListModel { id: dataModel ListElement { color: "orange"; text: "1" } ListElement { color: "skyblue"; text: "2" } ListElement { color: "orange"; text: "3" } ListElement { color: "skyblue"; text: "4" } ListElement { color: "orange"; text: "5" } ListElement { color: "skyblue"; text: "6" } ListElement { color: "orange"; text: "7" } ListElement { color: "skyblue"; text: "8" } ListElement { color: "orange"; text: "9" } ListElement { color: "skyblue"; text: "10" } } ScrollView { anchors.fill: parent anchors.margins: 10 GridView { id: view model: dataModel // 固定双列布局 columns: 2 // 自动计算列宽,刚好填满ScrollView宽度 cellWidth: parent.width / columns // 按4行高度分配单元格高度,确保可见区域刚好显示4行 cellHeight: parent.height / 4 // 保持从上到下的流排列顺序 flow: GridView.FlowTopToBottom delegate: Rectangle { width: view.cellWidth height: view.cellHeight color: model.color // 增加单元格间距优化视觉效果 margin: 5 Text { anchors.centerIn: parent text: model.text font.pointSize: 20 } } } } } }
关键修改说明
- ScrollView包裹GridView:自动处理超出内容的滚动逻辑,无需手动配置滚动条。
- 固定列数与动态单元格尺寸:
columns: 2强制双列布局,避免流布局自动调整列数。cellWidth: parent.width / columns让单元格宽度适配容器,两列刚好填满横向空间。cellHeight: parent.height / 4把容器高度平均分配给4行,确保可见区域刚好显示4组数据。
- 单元格间距优化:给delegate添加
margin,避免元素紧贴,提升界面美观度。
内容的提问来源于stack exchange,提问作者ARIPerm
相关产品推荐
相关产品推荐

