首页 文章

QML拖放(自由定位)

提问于
浏览
7

那里有很多QML拖放示例,但它们都没有真正帮助我,因为在所有示例中,您可以将一个元素拖动到另一个元素中,它在哪里居中,而上面拖动的所有其他元素都在它上面 .

有没有办法在一边有一些元素,另一边有一个大的 Rectangle 你可以把它们拖进去,放在它里面的任何地方它们都保持在它们的确切下落位置?

例如,如果我得到一个带有 width: 200; height: 200Rectangle 并且我拖入了一个元素,那么这个元素应该保持在我放弃它的位置,例如 x: 25y: 65 . 这应该是元素的位置 .

你有什么建议吗?

1 回答

  • 16

    设置 drag.target 以使 Item 可拖动非常简单,正如@qCring已经注意到的那样 . 删除拖动的 Item 根本不会改变它的位置 . 无论如何,也许这个小例子可以帮助你:

    import QtQuick 2.4
    import QtQuick.Window 2.2
    
    Window {
        id: win
        width: 800
        height: 600
        title: "Drag & drop example"
        visible: true
    
        Repeater {
            model: 10
            Rectangle {
                id: rect
                width: 50
                height: 50
                z: mouseArea.drag.active ||  mouseArea.pressed ? 2 : 1
                color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1)
                x: Math.random() * (win.width / 2 - 100)
                y: Math.random() * (win.height - 100)
                property point beginDrag
                property bool caught: false
                border { width:2; color: "white" }
                radius: 5
                Drag.active: mouseArea.drag.active
    
                Text {
                    anchors.centerIn: parent
                    text: index
                    color: "white"
                }
                MouseArea {
                    id: mouseArea
                    anchors.fill: parent
                    drag.target: parent
                    onPressed: {
                        rect.beginDrag = Qt.point(rect.x, rect.y);
                    }
                    onReleased: {
                        if(!rect.caught) {
                            backAnimX.from = rect.x;
                            backAnimX.to = beginDrag.x;
                            backAnimY.from = rect.y;
                            backAnimY.to = beginDrag.y;
                            backAnim.start()
                        }
                    }
    
                }
                ParallelAnimation {
                    id: backAnim
                    SpringAnimation { id: backAnimX; target: rect; property: "x"; duration: 500; spring: 2; damping: 0.2 }
                    SpringAnimation { id: backAnimY; target: rect; property: "y"; duration: 500; spring: 2; damping: 0.2 }
                }
            }
        }
    
        Rectangle {
            anchors {
                top: parent.top
                right:  parent.right
                bottom:  parent.bottom
            }
            width: parent.width / 2
            color: "gold"
            DropArea {
                anchors.fill: parent
                onEntered: drag.source.caught = true;
                onExited: drag.source.caught = false;
            }
        }
    }
    

    Item 可以拖入黄色框但不能退回 . 它只是为了好玩 .

相关问题