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

QtQuick/QML将项重设父级到GridLayout最后一个单元格失效问题

问题根因

你错误地假设GridLayout的children列表仅包含Repeater生成的单元格,实际第一个子元素是Repeater本身:

  • GridLayout的children列表索引0对应Repeater实例,索引1~20才是你生成的20个单元格元素
  • 当你传入最后一个单元格的索引19访问grid.children[19]时,实际取到的是第18个单元格;如果索引计算时误传超过20的数值,会出现parent绑定失败,元素自动以顶层Window为父渲染在左上角,看起来和第一个单元格位置重合
  • Grid组件出现相同问题也是同样的逻辑,只要使用Repeater生成子元素,布局的children列表都会先包含Repeater本身
解决方案

最稳妥的方式是直接通过Repeater的itemAt()方法获取指定索引的单元格,不需要手动计算children偏移,也不会因为后续给GridLayout加其他子元素导致索引失效,修改后的可运行示例如下:

import QtQuick
import QtQuick.Window
import QtQuick.Layouts 1.12

Window {
    width: 640
    height: 100
    visible: true

    GridLayout{
        columns: 10
        id: grid
        anchors.fill: parent
        Repeater{
            id: cellRepeater // 给Repeater设置id
            model: 10 * 2
            Rectangle{
                color: "lightblue"
                Layout.fillHeight: true
                Layout.fillWidth: true
            }
        }
    }

    Text{
        property int cellidx: 1
        parent: cellRepeater.itemAt(cellidx) // 通过Repeater获取对应单元格
        font.pointSize: 18
        font.bold: true
        text: cellidx
    }

    Text{
        property int cellidx: 18
        parent: cellRepeater.itemAt(cellidx)
        font.pointSize: 18
        font.bold: true
        text: cellidx
    }

    Text{
        property int cellidx: 19 // 最后一个单元格索引,可正常放置
        parent: cellRepeater.itemAt(cellidx)
        font.pointSize: 18
        font.bold: true
        text: cellidx
    }
}

如果坚持用children的方式访问,只需要把parent绑定改成grid.children[cellidx + 1]即可,不过该方式不推荐,后续给GridLayout新增子元素会导致索引偏移。

内容的提问来源于stack exchange,提问作者matthoe1212

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:36:04