ItemDragger.qml 2.22 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
// Idea from:
// https://stackoverflow.com/questions/42992067/qtquick-dragging-mapquickitem-on-a-map

import QtQuick      2.3
import QtLocation   5.3

import QGroundControl               1.0
import QGroundControl.ScreenTools   1.0
import QGroundControl.Controls      1.0

Rectangle {
    id:             root

    property var anchor: undefined
    property bool draggable: true
    readonly property bool dragged: mouseArea.drag.active

    signal dragStart
    signal dragStop
    signal clicked

    property bool _mobile:                  ScreenTools.isMobile
    property real _touchWidth:              Math.max(anchor.width, ScreenTools.minTouchPixels)
    property real _touchHeight:             Math.max(anchor.height, ScreenTools.minTouchPixels)
    property real _touchMarginHorizontal:   _mobile ? (_touchWidth - anchor.width) / 2 : 0
    property real _touchMarginVertical:     _mobile ? (_touchHeight - anchor.height) / 2 : 0


    x:              anchor.x - _touchMarginHorizontal
    y:              anchor.y - _touchMarginVertical
    width:          anchor.width + (_touchMarginHorizontal * 2)
    height:         anchor.height + (_touchMarginVertical * 2)
    color:          "transparent"
    z:              QGroundControl.zOrderMapItems + 1

    Component.onCompleted: {
        console.assert(anchor !== undefined, "please set the anchor property")
    }


    onDraggedChanged: {
        if (dragged) {
            dragStart()
        } else {
            dragStop()
        }
    }

    QGCMouseArea {
        id: mouseArea
        enabled: draggable
        preventStealing:    true
        drag.target: root
        drag.threshold: 0
        anchors.fill: parent
        cursorShape: draggable ?
                         (dragged ? Qt.ClosedHandCursor : Qt.OpenHandCursor)
                       : Qt.ArrowCursor
        onClicked: {
            focus = true
            root.clicked()
        }

    }

    Connections {
        target: anchor
        onXChanged: if (!dragged) x = anchor.x - _touchMarginHorizontal
        onYChanged: if (!dragged) y = anchor.y - _touchMarginVertical
    }

    onXChanged: if (dragged) anchor.x = x + _touchMarginHorizontal
    onYChanged: if (dragged) anchor.y = y + _touchMarginVertical

    Drag.active: true
}