【发布时间】:2021-04-01 11:05:25
【问题描述】:
此代码生成两个放置区域和一个可拖动的蓝色矩形。
我希望只能将蓝色矩形放置在金色放置区域中。另一个放置区域应该拒绝接受这个特定的矩形。
我可以写什么来实现这一点?
因此,在这段代码中,颜色为“gold”的 DropArea 具有键“xyz”,我已将 Drag.keys: "xyz" 设置为应该被拖动的蓝色矩形。
现在,那个蓝色矩形在另一个放置区域中被排除在外,但在金色区域中却没有。
我做错了什么?
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
id: win
width: 800
height: 600
title: "Drag & drop example"
visible: true
Repeater {
model: 1
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
Drag.keys: "xyz"
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
{
x: 0; y: 0
width: 200
height: 200
color: "gold"
DropArea {
anchors.fill: parent
keys: "xyz"
onEntered: drag.source.caught = true;
onExited: drag.source.caught = false;
}
}
Rectangle
{
x: 0; y: 300
width: 200
height: 200
color: "red"
DropArea {
anchors.fill: parent
keys: "abc"
onEntered: drag.source.caught = true;
onExited: drag.source.caught = false;
}
}
}
【问题讨论】: