Search code examples
qtdrag-and-dropqmlqtquick2qt6

How to make Drag element always on the top?


This is the Qt Drag and Drop Example.

43afccd0-7442-4aff-a706-1e1d5ca2d254-image.png

As you can see here, the 5th tile is under the 6th tile, and the 5th tile can be above of 4th tile.

enter image description here

But I want the dragging element to be always above of all the elements.

I've tried setting z of Rectangle in MouseArea to 1 or larger, but it didn't work.


Solution

  • Thanks for @folibis's help in comment, here is the answer for my quesiont. For anyone who has the same problem as me, you just need to specify a larger z for delegate whose drag.active of MouseArea is true.

    import QtQuick
    import QtQuick.Controls
    
    Window {
        width: 300
        height: 300
        visible: true
        color: "#1F1F1F"
        Column {
            anchors.centerIn: parent
            Repeater {
                model: 2
                delegate: Rectangle {
                    z: mouseArea.drag.active ? 2 : 0 // key
                    color: "#aaaaaa"
                    width: 300
                    height: 50
    
                    MouseArea {
                        id: mouseArea
                        anchors.fill: parent
                        drag.target: rec
    
                        Rectangle {
                            id: rec
                            color: "white"
                            height: parent.height / 2
                            width: parent.width / 2
                            anchors.verticalCenter: parent.verticalCenter
                            anchors.horizontalCenter: parent.horizontalCenter
                            Text {
                                anchors.centerIn: parent
                                text: "test " + index
                                color: "black"
                            }
                            states: [
                                State {
                                    when: mouseArea.drag.active
                                    AnchorChanges {
                                        target: rec
                                        anchors.verticalCenter: undefined
                                        anchors.horizontalCenter: undefined
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        }
    }
    
    

    This is a screenshot of running the above code:

    enter image description here