QML拖放(免费定位) [英] QML Drag and Drop (free positioning)
问题描述
在这里有很多QML拖放示例,但是没有一个真的帮助我,因为在所有的例子中,你可以将一个元素拖到另一个元素中间,其中所有其他元素都被放置在上面
There are a lot of QML Drag and Drop Examples out there, but none of them really helps me, because in all the examples you can drag an element into another, where it is centered and all other elements you drag above are laying over it.
有没有办法在一边有一些元素,另一边有一个大的 Rectangle
在那里你可以拖动它们,将它们放在它们的任何位置,并保持在他们确切的下降位置?
Is there a way to have some elements on one side and on the other side a big Rectangle
where you can drag them in, drop them anywhere inside of it and they stay on their exact drop position?
例如,如果我有一个矩形
与 width:200; height:200
我拖动一个元素,这样的元素应该保留在我放弃的位置,例如 x:25
和 y:65
。这应该是元素的位置。
For example, if I got a Rectangle
with width: 200; height: 200
and I drag an element in, such an element should stay at the position I've dropped it, e.g. x: 25
and y: 65
. That should be the position of the element.
你有什么建议吗?
推荐答案
只要将 drag.target
设置为 Item
draggable,这是非常简单的,如@qCring已经注意到了拖放的项目
根本不会更改其位置。无论如何,也许这个小例子可以帮助你:
It is very simple just to set drag.target
to make an Item
draggable, as @qCring already noticed. Dropping the dragged Item
doesn't change its position at all. Anyway, maybe this small example can help you:
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
can be dragged into yellow box but not back. Made it just for fun.
这篇关于QML拖放(免费定位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!