可拖动项目在 QML 中不起作用
Draggable items not working in QML
我正在尝试在 QML 中实现基本的拖放操作。从功能上讲,它可以工作——我可以四处拖动一根绳子。但是,我无法让我的可拖动 Rectangle 对象跟随光标。它将矩形的 x 和 y 正确设置为它变得可见的框架,但随后它保持静止而不是随鼠标移动。这是我的代码:
MouseArea {
id: mouseArea
anchors.fill: parent
drag.target: draggable
}
Rectangle {
id: draggable
height: 18
width: dragText.width + 8
clip: true
color: "#ff333333"
border.width: 2
border.color: "#ffaaaaaa"
visible: false
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
Drag.active: mouseArea.drag.active
Drag.hotSpot.x: 0
Drag.hotSpot.y: 0
Drag.mimeData: { "text/plain": "Teststring" }
Drag.dragType: Drag.Automatic
Drag.onDragStarted: {
visible = true
}
Drag.onDragFinished: {
visible = false
}
Text {
id: dragText
x: 4
text: "Teststring"
font.weight: Font.Bold
color: "#ffffffff"
horizontalAlignment: Text.AlignHCenter
}
}
您的矩形没有移动,因为您为您的矩形设置了锚点。锚旨在固定在锚点上。
删除
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
在您的 QML 中。
如果你想把它放在父级的中心,你需要这样设置:
x: parent.width / 2 - this.width / 2
y: parent.height / 2 - this.height / 2
您可能还想删除
Drag.dragType: Drag.Automatic
如果矩形在拖动结束后应该跟随您的光标,而不是仅仅移动。
我最终通过完全避免 Draggable 框架并基本上只使用变通方法解决了这个问题。我将以下内容添加到我的 MouseArea 以使矩形正确移动:
onMouseXChanged: {
draggable.x = mouseX - draggable.width/2
}
onMouseYChanged: {
draggable.y = mouseY - draggable.height/2
}
为了模拟放置功能,我以编程方式计算 "drop area," 的位置,将其与具有基本碰撞检测的鼠标位置进行比较,然后附加到附加到 "drop area."[= 的 ListView 11=]
我正在尝试在 QML 中实现基本的拖放操作。从功能上讲,它可以工作——我可以四处拖动一根绳子。但是,我无法让我的可拖动 Rectangle 对象跟随光标。它将矩形的 x 和 y 正确设置为它变得可见的框架,但随后它保持静止而不是随鼠标移动。这是我的代码:
MouseArea {
id: mouseArea
anchors.fill: parent
drag.target: draggable
}
Rectangle {
id: draggable
height: 18
width: dragText.width + 8
clip: true
color: "#ff333333"
border.width: 2
border.color: "#ffaaaaaa"
visible: false
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
Drag.active: mouseArea.drag.active
Drag.hotSpot.x: 0
Drag.hotSpot.y: 0
Drag.mimeData: { "text/plain": "Teststring" }
Drag.dragType: Drag.Automatic
Drag.onDragStarted: {
visible = true
}
Drag.onDragFinished: {
visible = false
}
Text {
id: dragText
x: 4
text: "Teststring"
font.weight: Font.Bold
color: "#ffffffff"
horizontalAlignment: Text.AlignHCenter
}
}
您的矩形没有移动,因为您为您的矩形设置了锚点。锚旨在固定在锚点上。
删除
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
在您的 QML 中。
如果你想把它放在父级的中心,你需要这样设置:
x: parent.width / 2 - this.width / 2
y: parent.height / 2 - this.height / 2
您可能还想删除
Drag.dragType: Drag.Automatic
如果矩形在拖动结束后应该跟随您的光标,而不是仅仅移动。
我最终通过完全避免 Draggable 框架并基本上只使用变通方法解决了这个问题。我将以下内容添加到我的 MouseArea 以使矩形正确移动:
onMouseXChanged: {
draggable.x = mouseX - draggable.width/2
}
onMouseYChanged: {
draggable.y = mouseY - draggable.height/2
}
为了模拟放置功能,我以编程方式计算 "drop area," 的位置,将其与具有基本碰撞检测的鼠标位置进行比较,然后附加到附加到 "drop area."[= 的 ListView 11=]