Qt Quick开发教程4-QML拖放

在文本/富文本编辑器中,常用到拖放动作.

import QtQuick 2.2
import "../shared" as Examples

Rectangle {
    id: item
    property string display
    property alias dropEnabled: acceptDropCB.checked
    color: dropArea.containsDrag ? "#CFC" : "#EEE"
    ColorAnimation on color {
        id: rejectAnimation
        from: "#FCC"
        to: "#EEE"
        duration: 1000
    }
    //要显示的文本
    Text {
        anchors.fill: parent
        text: item.display
        wrapMode: Text.WordWrap
    }
    //放下动作区域设置:
    DropArea {
        id: dropArea
        anchors.fill: parent
        keys: ["text/plain"]    //只接受这个属性"text/plain"的放下动作
        onEntered: if (!acceptDropCB.checked) {    //当鼠标进入该区域时,如果不接受放下,那就显示拒绝动画
            drag.accepted = false
            rejectAnimation.start()
        }
        onDropped: if (drop.hasText && acceptDropCB.checked) { //当鼠标在该区域释放,把其中的文本取出来,并显示
            if (drop.proposedAction == Qt.MoveAction || drop.proposedAction == Qt.CopyAction) {
                item.display = drop.text
                drop.acceptProposedAction()
            }
        }
    }
    //拖走动作需要在MouseArea区域里设置,因为拖动是属于MouseArea的一部分
    MouseArea {
        id: mouseArea
        anchors.fill: parent
        drag.target: draggable
    }
    //软件是拖走一端的时候要实现的部分
    //拖走动作的实现:当MouseArea的拖走激活,他也激活,mimeData指定了拖动的数据内容,拖动类型设置为自动,
    Item {
        id: draggable
        anchors.fill: parent
        Drag.active: mouseArea.drag.active
        Drag.hotSpot.x: 0
        Drag.hotSpot.y: 0
        Drag.mimeData: { "text/plain": item.display }
        Drag.dragType: Drag.Automatic
        Drag.onDragFinished: if (dropAction == Qt.MoveAction) item.display = ""
    }
    Examples.CheckBox {
        id: acceptDropCB
        anchors.right: parent.right
        checked: true
        text: "accept drop"
    }
}

原文地址:https://www.cnblogs.com/charleechan/p/12340856.html