【问题标题】:Draggable items not working in QML可拖动项目在 QML 中不起作用
【发布时间】:2016-12-02 21:57:07
【问题描述】:

我正在尝试在 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
    }
}

【问题讨论】:

  • 你要在这里做什么?您是否尝试使用visible: false 拖动项目?
  • 不,我将项目设置为在拖动开始后立即可见(请参阅 Drag.onDragStarted)。
  • 拖动隐形物品有什么意义?你的目标是什么?也许这可以通过另一种方式来完成。
  • 可见性并不重要。如果我将对象设置为可见,它仍然不能正确拖动。在你开始拖动之前,我只是隐藏了拖动对象。

标签: drag-and-drop qml draggable qtquick2


【解决方案1】:

您的矩形没有移动,因为您为矩形设置了锚点。锚点旨在固定在锚定点上。

删除

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

拖动结束后矩形是否应该跟随光标移动,而不是仅仅移动。

【讨论】:

  • 所以,我还有一些问题。当我删除 Drag.dragType: Drag.Automatic 时,矩形会正确移动,但“拖动”状态永远不会出现。因此,我必须在实际拖动文本(功能)与随光标移动的矩形(可视化)之间做出选择。我想要两者。
  • 像上面的匿名用户一样,我想要一个既能正常拖动又能触发拖动事件并触发拖动状态的解决方案
【解决方案2】:

我最终通过完全避免使用 Draggable 框架并且基本上只是使用变通方法来解决这个问题。我将以下内容添加到我的 MouseArea 以使矩形正确移动:

onMouseXChanged: {
    draggable.x = mouseX - draggable.width/2
}
onMouseYChanged: {
    draggable.y = mouseY - draggable.height/2
}

为了模拟放置功能,我以编程方式计算“放置区域”的位置,通过基本的碰撞检测将其与鼠标位置进行比较,然后附加到附加到“放置区域”的 ListView。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-15
    • 2015-08-03
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2019-03-29
    • 1970-01-01
    相关资源
    最近更新 更多