QML中如何围绕自定义指定点旋转Item组件?
QML Item围绕自定义点旋转的问题解决
你的代码核心问题在于直接修改了Item的rotation属性,这会覆盖你通过Rotation transform定义的自定义旋转支点设置。当你直接设置Item的rotation时,QML会默认使用transformOrigin作为旋转中心,完全忽略你在Rotation组件里配置的origin。
要实现围绕自定义点旋转,你需要:
- 给
Rotation组件设置id,通过修改它的angle属性来控制旋转 - 动画和状态变更都针对
Rotation的angle,而非Item的rotation
修正后的代码如下:
Item { id: mainItem transform: Rotation { id: customRotation origin.x: 20 origin.y: 20 } Rectangle { anchors.fill: parent color: "transparent" border.color: "white" Component.onCompleted: state = "rotated" transitions: Transition { RotationAnimation { target: customRotation property: "angle" duration: 10000 direction: RotationAnimation.Clockwise } } states: State { name: "rotated" PropertyChanges { target: customRotation angle: 360 } } } }
关键说明:
Rotation组件的origin属性确实是旋转支点,它的坐标是相对于mainItem自身的左上角(Item的本地坐标系)- 不要混用Item的
rotation属性和Rotationtransform组件,二者是独立的旋转控制方式:- 直接设置
rotation:使用默认transformOrigin,适合简单的中心/边缘旋转 - 使用
Rotationtransform:可以自定义任意旋转支点,需要通过修改其angle属性来驱动旋转
- 直接设置
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

