qml鼠标拖动,如何在QML中使项目在圆内拖动?

Below code allows the small red coloured rectangle to be dragged in an area which is a rectangle defined by minimum and maximum drag values.

I want it to go on only up till the boundary of the parent rectangle whose radius is 100 which means that it is now a circle.

How to make an item drag inside a circle in QML?

Window {

width: 200; height: 200; visible: true

Rectangle

{

x: 10; y: 10

width: 200; height: 200

radius: 100

color: "blue"

Rectangle {

x: 10; y: 10

width: 20; height: 20

color: "red"

MouseArea

{

id: dragArea

anchors.fill: parent

drag.target: parent

drag.minimumX : 20

drag.maximumX : 150

drag.minimumY : 20

drag.maximumY : 150

}

}

}

}

解决方案

So I found some time to provide the aforementioned smoother solution.

import QtQuick 2.5

import QtQuick.Window 2.2

Window {

id: root

visible: true

width: 640

height: 480

title: qsTr("Hello World")

property int radius: 100

Rectangle {

id: circle

width: 2 * radius

height: 2 * radius

radius: root.radius

color: 'blue'

}

Rectangle {

id: mark

width: 20

height: 20

x: (dragObj.dragRadius <= root.radius ? dragObj.x : root.radius + ((dragObj.x - root.radius) * (root.radius / dragObj.dragRadius))) - 10

y: (dragObj.dragRadius <= root.radius ? dragObj.y : root.radius + ((dragObj.y - root.radius) * (root.radius / dragObj.dragRadius))) - 10

color: 'red'

MouseArea {

id: markArea

anchors.fill: parent

drag.target: dragObj

onPressed: {

dragObj.x = mark.x + 10

dragObj.y = mark.y + 10

}

}

}

Item {

id: dragObj

readonly property real dragRadius: Math.sqrt(Math.pow(x - root.radius, 2) + Math.pow(y - root.radius, 2))

x: root.radius

y: root.radius

onDragRadiusChanged: console.log(dragRadius)

}

}

I use the dragObj to avoid the limitations of my dragging position. This spans a vector from the center of the circle. As long as the dragObj itself is contained in the circle, I will use it's position as the position of the marker.

But once it leaves the circle, I will project the vector on the circle, so it will stay within the limits.

To ensure, that every drag starts again on the mark, I will reset the position of the dragObj to the position of the mark, when ever the mouse is pressed again (precondition for a new drag-event)

Have fun with it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值