0
votes

I am trying to understand how to use the QML's drag-and-drop functionality. For that reason I have modified the first example in the documentation of Drag QML Type like this:

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 400
    height: 400
    visible: true

    Item {
        anchors.fill: parent

        DropArea {
            x: 100; y: 100; width: 100; height: 100

            onEntered: console.log("entered")
            onExited: console.log("exited")
            onPositionChanged: console.log("dragged to (" + drag.x + ", "
                                           + drag.y + ")")
            onDropped: console.log("dropped")

            Rectangle {
                anchors.fill: parent
                color: parent.containsDrag ? "green" : "yellow"
            }
        }

        Rectangle {
            x: 10; y: 10; width: 50; height: 50
            color: "red"

            Drag.active: dragArea.drag.active
            Drag.hotSpot.x: 25
            Drag.hotSpot.y: 25

            MouseArea {
                id: dragArea
                anchors.fill: parent
                drag.target: parent
            }
        }
    }
}

As a result I expect dropped to be logged in the console when I drag the red rectangle over the drop area and drop it there. Instead, I get exited:

qml: entered
qml: dragged to (2, 1)
qml: dragged to (3, 2)
qml: dragged to (5, 3)
qml: dragged to (5, 4)
...
qml: dragged to (44, 39)
qml: dragged to (45, 40)
qml: dragged to (46, 40)
qml: exited <- Shouldn't this be 'dropped'

The similar questions, e.g.:

DropArea doesn't notify about actions onEntered, onExited, onDropped

does not offer a solution to the described problem.

How to make this work as expected?

1
As for me the Drag&Drop system in QML is just disgusting. You maybe have to play with Drag.dragType. As I remeber if that isn't Automatic you have to start and stop it programatically.folibis
Or try this solution, that should help you.folibis
As for me the Drag&Drop system in QML is just disgusting I feel the same way. Thank you for the hints and the link!scopchanov
@folibis, That is sick, really. It turns out, that although I was able to move the rectangle, this was not considered as a dragging at all. :( Thanks to you, now I understand it better. May I ask you to write this as an answer, so I can accept it.scopchanov

1 Answers

3
votes

The problem is in the following line:

Drag.active: dragArea.drag.active

From the documentation about Drag.active property:

Setting this property to true will also send a QDragEnter event to the scene with the item's current position. Setting it to false will send a QDragLeave event.

So when you release the mouse button, MouseArea changes drag.active property to false and you get exited signal. Try to add to your MouseArea: onReleased: parent.Drag.drop()

I would say Qt has bad example for Qml drag-and-drop.