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

QML中如何利用其他Item的rotation属性旋转点并绘制正确线段?

问题描述

我想在QML中绘制一条从(0, 0)到某个Rectangle左上角的线段,但该Rectangle已通过rotation属性(旋转原点为Item.BottomRight)进行了30度旋转。当前代码运行后无法得到预期效果,请问如何借助该Rectangle的rotation属性对目标点进行旋转计算,以绘制出正确的线段?

当前代码:

Rectangle {
    id: rect
    color: "blue"
    x: 0
    y: 0
    width: 70
    height: 150
    rotation: 30
    transformOrigin: Item.BottomRight
}

Shape {
    ShapePath {
        strokeColor: "red"
        startX: 0
        startY: 0
        PathLine {x: rect.x; y: rect.y}
    }
}

当前效果:
线段指向错误的矩形

解决方案

你直接用rect.x和rect.y拿的是矩形未旋转前的左上角坐标,旋转后实际的左上角位置已经偏移,所以线段指向错误。有两种方法可以解决:

方法一:手动坐标变换计算

通过三角函数计算旋转后的左上角绝对坐标,步骤如下:

  1. 确定旋转原点的绝对坐标:旋转原点是Item.BottomRight,对应坐标为(rect.x + rect.width, rect.y + rect.height)
  2. 计算矩形左上角相对于旋转原点的原始偏移:未旋转时为(-rect.width, -rect.height)
  3. 将偏移量按旋转角度转换为弧度后做旋转变换
  4. 旋转后的左上角坐标 = 旋转原点坐标 + 变换后的偏移量

修改后的Shape代码:

Shape {
    ShapePath {
        strokeColor: "red"
        startX: 0
        startY: 0
        PathLine {
            var originX = rect.x + rect.width
            var originY = rect.y + rect.height
            var offsetX = -rect.width
            var offsetY = -rect.height
            var rad = rect.rotation * Math.PI / 180
            var rotatedOffsetX = offsetX * Math.cos(rad) - offsetY * Math.sin(rad)
            var rotatedOffsetY = offsetX * Math.sin(rad) + offsetY * Math.cos(rad)
            
            x: originX + rotatedOffsetX
            y: originY + rotatedOffsetY
        }
    }
}

方法二:使用QML内置映射方法(推荐)

利用mapToItem方法直接将矩形自身坐标系下的左上角(0,0)映射到根坐标系,自动处理所有变换(旋转、平移等),代码更简洁:

Shape {
    ShapePath {
        strokeColor: "red"
        startX: 0
        startY: 0
        PathLine {
            x: rect.mapToItem(null, 0, 0).x
            y: rect.mapToItem(null, 0, 0).y
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 23:02:38