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

前端 未结 2 1461
自闭症患者
自闭症患者 2021-02-10 15:08

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 t

2条回答
  •  遥遥无期
    2021-02-10 16:12

    A little bit late, but I was up for some quiz.

    Here is a imperfect solution, with some flaws.

    import QtQuick 2.5
    import QtQuick.Window 2.2
    
    Window {
        width: 400; height: 400; 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 : Math.ceil(100 - Math.sqrt(200 * parent.y - Math.pow(parent.y, 2)))
                    drag.maximumX : Math.floor(Math.sqrt(200 * parent.y - Math.pow(parent.y, 2)) + 100)
    
                    drag.minimumY : Math.ceil(100 - Math.sqrt(200 * parent.x - Math.pow(parent.x, 2)))
                    drag.maximumY : Math.floor(Math.sqrt(200 * parent.x - Math.pow(parent.x, 2)) + 100)
                }
            }
        }
    }
    

    The idea is, that you calculate the max- and min-values of x and y depending on the current value of y and x (so max-x is depending on current-y, and max-y is depending on current-x)

    The function behind that is: (r - y)² + (r - x)² = r²

    What I did not incorporate is the dimension of the small draggable Rectangle. So I only force the top-left corner to stay within the circles bounds. This however should be easy to adapt. To account for that, assume a circle, with half the rectangles width/height less radius, and shift it by half the rectangles width/height.

    Another flaw is, that if I reach one of the limits (top, left, right, bottom) the Rectangle might flicker and does not follow the mouse smoothly.

    To fix that, you can use an invisible object as helper, that can be freely drawn around, and you then use it's position to calculate the red Rectangles position that is shown.

    Maybe I will add an implementation for that later as well. I am pretty sure, this should work pretty smoothly.

提交回复
热议问题