首页 文章

如何让DragArea的拖放效果为接收它的DropArea设置动画效果?

提问于
浏览
7

希望这可以作为一个问题 . 在我的应用程序中,我有一个 DragArea 定义,我用它来开始拖动各种矩形的顶部,每个矩形包含 DropArea . 除了我想改变的美容效果之外,我的代码中的一切都运行良好 .

在QML中,当您从 DragArea 开始拖动并最终掉落时,动画效果会使您拖动的内容动画(同时淡出)回到您开始拖动的位置 . 即使您成功捕获掉落的 DropArea ,也会发生这种情况 .

我想做的是让接收掉落的 DropArea 具有下拉效果动画 - 这样看起来我将东西拖放到矩形中 . 有没有办法做到这一点?

我猜这在某种程度上涉及这些区域的.source和.target属性,但到目前为止,对于放置动画的位置有任何影响都没有运气 .

1 回答

  • 2

    默认情况下,QML不会为您提供拖放的整容行为 . 拖动目标将从拖动开始位置开始,无论是否接受拖动,拖动目标都将在拖放的任何位置结束 .

    因此,我假设您描述的行为是在您的用户代码中实现的,您尚未公开 . 无论如何,您想要做的事情非常简单,它涉及跟踪拖动起始位置和结束位置,因此您可以使用两个坐标来为位置设置动画 .

    在下面的示例中,可以拖动红色矩形,如果拖放到拖放区域之外,它将从其当前位置动画到其初始位置,而如果放入黄色矩形,则会从其初始位置动画到其放置位置 .

    Window {
      width: 600
      height: 600
      visible: true
    
      Rectangle {
        width: 200
        height: 200
        color: "yellow"
        DropArea {
          anchors.fill: parent
          onEntered: drag.source.accepted = true
          onExited: drag.source.accepted = false
        }
      }
    
      Rectangle {
        id: rect
        width: 50
        height: 50
        color: "red"
        x: parent.width * 0.5
        y: parent.height * 0.5
        Drag.active: mouseArea.drag.active
    
        property point begin
        property point end
        property bool accepted : false
    
        MouseArea {
          id: mouseArea
          anchors.fill: parent
          drag.target: parent
          onPressed: rect.begin = Qt.point(rect.x, rect.y)
          onReleased: {
            rect.end = Qt.point(rect.x, rect.y)
            aX.from = rect.accepted ? rect.begin.x : rect.end.x
            aX.to = rect.accepted ? rect.end.x : rect.begin.x
            aY.from = rect.accepted ? rect.begin.y : rect.end.y
            aY.to = rect.accepted ? rect.end.y : rect.begin.y
            anim.start()
          }
          ParallelAnimation {
            id: anim
            NumberAnimation { id: aX; target: rect; property: "x"; duration: 200 }
            NumberAnimation { id: aY; target: rect; property: "y"; duration: 200 }
          }
        }
      }
    }
    

相关问题