Qt Quick 示例 - 拖放
这是一组 QML 拖放示例。

“拖放”是一组与拖放功能相关的小型 QML 示例。如需了解更多信息,请访问“拖放”页面。
运行示例
您可以通过以下方式运行示例:
- Qt Creator
打开Welcome 模式,并从Examples 中选择该示例。如需了解更多信息,请参阅Qt Creator :教程:构建和运行。
- Qt Extension for Visual Studio Code
在Command Palette 中运行Qt: Open Qt examples 命令,并从列表中选择该示例。有关详细信息,请参阅Qt Extension for Visual Studio Code :教程:构建和运行。
Tiles
“Tiles”为简单的矩形添加了拖放功能,您可以将其拖放到特定的网格中。
它包含一个 DragTile 组件,该组件使用MouseArea 在拖动时移动项目:
Item {
id: root
required property string colorKey
required property int modelData
width: 64
height: 64
MouseArea {
id: mouseArea
width: 64
height: 64
anchors.centerIn: parent
drag.target: tile
onReleased: parent = tile.Drag.target !== null ? tile.Drag.target : root
Rectangle {
id: tile
width: 64
height: 64
anchors {
verticalCenter: parent.verticalCenter
horizontalCenter: parent.horizontalCenter
}
color: root.colorKey
Drag.keys: [ root.colorKey ]
Drag.active: mouseArea.drag.active
Drag.hotSpot.x: 32
Drag.hotSpot.y: 32
states: State {
when: mouseArea.drag.active
AnchorChanges {
target: tile
anchors {
verticalCenter: undefined
horizontalCenter: undefined
}
}
}
}
}
}此外还有一个 DropTile 组件,被拖动的方块可以放置在其上:
DropArea {
id: dragTarget
property string colorKey
width: 64
height: 64
keys: [ colorKey ]
Rectangle {
id: dropRectangle
anchors.fill: parent
color: dragTarget.containsDrag ? "grey" : dragTarget.colorKey
}
}DropArea 的keys属性仅允许在该组件上放置与Drag.keys属性中键值匹配的项目。
GridView 示例
GridView 示例为 GridView 添加了拖放功能,允许您在不更改底层ListModel 的情况下,直观地重新排序委托项。它使用DelegateModel 将委托项移动到其拖动经过的另一个项的位置。
model: DelegateModel {
delegate: DropArea {
id: delegateRoot
required property color color
width: 80
height: 80
onEntered: function(drag) {
visualModel.items.move((drag.source as Icon).visualIndex, icon.visualIndex)
}
property int visualIndex: DelegateModel.itemsIndex
Icon {
id: icon
dragParent: root
visualIndex: delegateRoot.visualIndex
color: delegateRoot.color
}
}© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.