Qt Quick 示例 - 拖放

这是 QML 拖放示例集。

拖放是与拖放功能有关的小型 QML 示例集。更多信息,请访问拖放页面。

运行示例

要从 Qt Creator,打开Welcome 模式,并从Examples 选择示例。更多信息,请参阅Qt Creator: 教程:构建并运行

瓷砖

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 添加了拖放功能,使您可以在不改变底层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
            }
        }

示例项目 @ code.qt.io

© 2025 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.