ndo*_*ing 7 drag-and-drop qml qt-quick qtquick2
那里有很多QML拖放示例,但它们都没有真正帮助我,因为在所有示例中,您可以将一个元素拖动到另一个元素中,它在哪里居中,而上面拖动的所有其他元素都在它上面.
有没有办法在一侧有一些元素,在另一侧有一个大的Rectangle
地方可以拖入它们,将它们放在它内部的任何地方并且它们保持在它们的确切下落位置?
举例来说,如果我有一个Rectangle
与width: 200; height: 200
我在,这样的元素应该留在我已经放弃了它的位置,例如拖动的元素x: 25
和y: 65
.这应该是元素的位置.
你有什么建议吗?
fol*_*bis 19
设置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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Item
可以拖到黄色的盒子但不能回来.它只是为了好玩.