Drag and Drop in QML TreeView with multiselection



  • How can I implement drag & drop in a QtQuick TreeView without breaking the selection mechanism?

    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;
                    }
                }
            }
        }
    }
    

    The MouseArea inside the itemDelegate seems to be the common solution for drag and drop in TreeViews, but the selection does not work anymore if I add it.
    So I can only make the selection OR the drag and drop work properly :-(

    Any help would be appreciated!

    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!



  • By adding the line "property alias mouser: mouseArea" to the TreeView.qml of Qt, I can implement mouser.onPressed: {...} inside my TreeView code.
    This way both the selection and drag&drop work, but I actually don't like the idea of modifying Qt code.

    No one out there with an approach how to solve this a bit cleaner?



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.