Search code examples
qml

onDropped not being triggered in QML


I am trying to implement a drag and drop functionality, I can successfully drag and drop the item, but whenever the item is dropped into the dropArea the onDropped handler is not being invoked but all other handlers like onExited, onPositionChanged and onEntered is being invoked.

This is my DragItem Component:

import QtQuick

Item {
    id: root
    required property string colorKey
    width: 64
    height: 64

    MouseArea {
        id: mouseArea
        width: 64
        height: 64
        anchors.centerIn: parent
        drag.target: item
        onReleased: {
            console.log("Item Released")
             parent = item.Drag.target !== null ? item.Drag.target : root
        }
        Rectangle {
            id: item
            width: 64
            height: 64
            anchors {
                verticalCenter: parent.verticalCenter
                horizontalCenter: parent.horizontalCenter
            }

            color: root.colorKey
            Drag.keys: [ root.colorKey ]
            Drag.active: mouseArea.drag.active
            Drag.hotSpot.x: 32
            Drag.hotSpot.y: 32
            states: State {
                when: mouseArea.drag.active
                AnchorChanges {
                    target: item
                    anchors {
                        verticalCenter: undefined
                        horizontalCenter: undefined
                    }
                }
            }
        }
    }
}

and this is my dropArea:

DropArea{
        id: visualizer
        width: mainWindow.width / 2
        height: mainWindow.height - toolBar.height
        anchors.top: toolBar.bottom
        anchors.left: dragRect.right
        anchors.right: mainWindow.right
        visible: true

        property string colorKey
        //keys: [ "black", "skyblue" ]

        // Handle the drop event
        // this is not being invoked..
        onDropped: {
            // Access the color key of the dropped item
            console.log("Dropped")

        }

        onEntered: {
            console.log("Entered")
        }

        onExited: {
            console.log("Exited")
        }

        onPositionChanged: {
            console.log("Position Changed")
        }
    }
}

Solution

  • You must call drop() on your dragged item:

    onReleased: (mouse) => {
                console.log("Item Released")
                // parent = item.Drag.target !== null ? item.Drag.target : root
    
                // drop the item
                item.Drag.drop();
            }