You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:07:14