Drag and Drop in QML TreeView

1.2k views Asked by At

In QML i have a TreeView with (properly working) multiselection:

TreeView {
    id: treeview
    anchors.fill: parent
    model: myTestModel

    selectionMode: SelectionMode.ExtendedSelection
    selection: ItemSelectionModel {
        model: treeview.model
    }

    TableViewColumn {
        role: "name_role"
        title: "Name"
        width: 160
    }
    TableViewColumn {
        role: "type_role"
        title: "Type"
        width: 75
    }
}

I'd like to implement drag & drop to be able to "pull" items out of the treeview into a DropArea.

But when I use the approach I found several times, namely defining an itemDelegate that contains a MouseArea, the selection doesn't work anymore.

TreeView {
    id: treeview
    anchors.fill: parent
    model: myTestModel

    // broken due to MouseArea in itemDelegate !
    selectionMode: SelectionMode.ExtendedSelection
    selection: ItemSelectionModel {
        model: treeview.model
    }

    TableViewColumn {
        role: "name_role"
        title: "Name"
        width: 160
    }
    TableViewColumn {
        role: "type_role"
        title: "Type"
        width: 75
    }

    itemDelegate: Item {
        Rectangle {
            id: rect
            anchors.fill: parent
            color: styleData.selected ? "blue" : "transparent"
            Text {
                anchors.verticalCenter: parent.verticalCenter
                color: styleData.selected ? "white" : "black"
                text: styleData.value
            }
            MouseArea {
                anchors.fill: parent
                drag.target: symbolAvatar
                onPressed: {
                    var tmp = mapToItem(container, mouse.x, mouse.y);
                    symbolAvatar.x = tmp.x;
                    symbolAvatar.y = tmp.y;
                    symbolAvatar.dragging = true;
                    symbolAvatar.text = styleData.value;
                }
            }
        }
    }
}

where symbolAvatar is an item that becomes visible when a drag has started.

Any ideas how to implement drag and drop in a QML TreeView without breaking the selection?

Edit: Using the onPressAndHold event handler inside the TreeView would be a solution if I could access the mouse position there, but it doesn't seem to exist :-(

0

There are 0 answers