下面的例子代码来自官方文档:
http://qt-project.org/doc/qt-5/qml-qtquick-drag.html
import QtQuick 2.0
Item {
width: 200; height: 200
DropArea {
x: 75; y: 75
width: 50; height: 50
Rectangle {
anchors.fill: parent
color: "green"
visible: parent.containsDrag
}
}
Rectangle {
x: 10; y: 10
width: 20; height: 20
color: "red"
Drag.active: dragArea.drag.active
Drag.hotSpot.x: 10
Drag.hotSpot.y: 10
MouseArea {
id: dragArea
anchors.fill: parent
drag.target: parent
}
}
}$ ~/Qt5.2.0/5.2.0/gcc_64/bin/qmlscene ./try.qml首先显示了一个200*200的窗口
这个红色的方块是可以被拖拽的,当拖到窗口中间的时候,会出现绿色大方块。
这个绿色的区域就是DropArea,里面定义了一个Rectangle,当containsDrag被设置为true时就显示。
containsDrag表示是否有东西拖拽进来。参考:http://qt-project.org/doc/qt-5/qml-qtquick-droparea.html#containsDrag-prop
Drag.active需要绑定到MouseArea.drag.active,也就是允许拖拽的区域。当用户开始在MouseArea区域拖拽时,内部的startDrag方法会被调用。
参考文档:http://qt-project.org/doc/qt-5/qml-qtquick-drag.html#active-prop
现在测试一下两个事件,一个是当拖进DropArea的onEntered事件,一个是当拖拽结束(松开鼠标)的onDropped事件。
注意,要想第二个onDropped事件发生,DrapArea(也就是MouseArea)必须显示的调用drop方法。
import QtQuick 2.0
Item {
width: 200; height: 200
DropArea {
x: 75; y: 75
width: 50; height: 50
onEntered: console.log("entered")
onDropped: console.log("dropped")
Rectangle {
id: x
anchors.fill: parent
color: "green"
visible: parent.containsDrag
}
}
Rectangle {
x: 10; y: 10
width: 20; height: 20
color: "red"
Drag.active: dragArea.drag.active
Drag.hotSpot.x: 10
Drag.hotSpot.y: 10
MouseArea {
id: dragArea
anchors.fill: parent
onReleased: parent.Drag.drop()
drag.target: parent
}
}
}现在可以在控制台上看到拖拽的日志了。
entered dropped entered entered dropped
原文:http://blog.csdn.net/csfreebird/article/details/18258361