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

QML如何在Repeater内正确设置矩形组件的坐标?

解决QML中Repeater在Grid内设置坐标无效的问题

问题核心原因

你遇到的问题本质是Grid容器会强制管理子项的布局位置——不管你在子项里设置x/y还是锚点,都会被Grid的行列布局逻辑覆盖,这就是红色矩形要么重叠在同一单元格、要么自定义坐标不生效的原因。

解决方案

根据需求提供两种常用解决思路:


思路1:让红色矩形脱离Grid的布局控制

如果不需要Grid来排列红色矩形,直接将Repeater移到Grid的父容器(gameWindow)下,或者给红色矩形指定父容器为gameWindow,就能自由设置坐标:

import QtQuick

Window {
   id: mainWindow
   property int wi: 640
   property int he: 500
   width: wi
   height: he
   visible: true
   title: qsTr("Game")

Rectangle {
    id: gameWindow
    width: wi/1.6
    height: he
    anchors.right: parent.right
    visible: true
    color: "black"
    clip: true

    Grid {
        id: gameGrid
        columns: 25
        spacing: 0
        rows: 32
        anchors.fill: parent

        Repeater {
            model: 600
            Rectangle {
                width: wi/40
                height: 20
                border.width: 2
                color: "grey"
            }
        }
    }

    // 直接在gameWindow下放置红色矩形的Repeater,脱离Grid布局
    Repeater {
        model: 5
        Rectangle {
            // 按index计算横向排列的坐标
            x: gameWindow.width/2 + index * (wi/40)
            y: gameWindow.height/2
            width: wi/40
            height: 20
            border.width: 1
            color: "red"
        }
    }
}
}

思路2:在Grid内指定红色矩形的行列位置

如果必须保留Grid作为父容器,可以通过Grid.column和Grid.row属性手动指定每个红色矩形的单元格位置:

import QtQuick

Window {
   id: mainWindow
   property int wi: 640
   property int he: 500
   width: wi
   height: he
   visible: true
   title: qsTr("Game")

Rectangle {
    id: gameWindow
    width: wi/1.6
    height: he
    anchors.right: parent.right
    visible: true
    color: "black"
    clip: true

    Grid {
        id: gameGrid
        columns: 25
        spacing: 0
        rows: 32
        anchors.fill: parent

        Repeater {
            model: 600
            Rectangle {
                width: wi/40
                height: 20
                border.width: 2
                color: "grey"
            }
        }
    }

    Grid {
        id: sGrid
        columns: gameGrid.columns
        spacing: gameGrid.spacing
        rows: gameGrid.rows
        anchors.fill: gameGrid

        Repeater {
            model: 5
            Rectangle {
                // 指定从第10列开始,每个矩形占一列
                Grid.column: 10 + index
                // 固定在第16行(中间行)
                Grid.row: 16
                width: wi/40
                height: 20
                border.width: 1
                color: "red"
            }
        }
    }
}
}

额外说明

  • Repeater的子项本身就是它的delegate,不需要额外添加delegate关键字,你之前的写法是正确的。
  • 锚点布局在Grid内无效,因为Grid会强制重置子项的位置属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:01:01