Nesta página

Tutorial 2 sobre ordenação dinâmica de visualizações no QML – Arrastando itens da visualização

Agora que temos uma lista visível de itens, queremos poder interagir com eles. Começaremos estendendo o delegado para que o conteúdo visível possa ser arrastado para cima e para baixo na tela. O delegado atualizado fica assim:

    Component {
        id: dragDelegate

        MouseArea {
            id: dragArea

            property bool held: false
            required property string name
            required property string type
            required property string size
            required property int age

            anchors {
                left: parent?.left
                right: parent?.right
            }
            height: content.height

            drag.target: held ? content : undefined
            drag.axis: Drag.YAxis

            onPressAndHold: held = true
            onReleased: held = false

            Rectangle {
                id: content
                anchors {
                    horizontalCenter: parent.horizontalCenter
                    verticalCenter: parent.verticalCenter
                }
                width: dragArea.width
                height: column.implicitHeight + 4

                border.width: 1
                border.color: "lightsteelblue"
                color: dragArea.held ? "lightsteelblue" : "white"
                Behavior on color { ColorAnimation { duration: 100 } }
                radius: 2
                states: State {
                    when: dragArea.held

                    ParentChange {
                        target: content
                        parent: root
                    }
                    AnchorChanges {
                        target: content
                        anchors {
                            horizontalCenter: undefined
                            verticalCenter: undefined
                        }
                    }
                }
                Column {
                    id: column
                    anchors {
                        fill: parent
                        margins: 2
                    }

                    Text { text: qsTr('Name: ') + dragArea.name }
                    Text { text: qsTr('Type: ') + dragArea.type }
                    Text { text: qsTr('Age: ') + dragArea.age }
                    Text { text: qsTr('Size: ') + dragArea.size }
                }
            }
        }
    }
Passo a passo

A principal mudança aqui é que o item raiz do delegado agora é um ` MouseArea `, que fornece manipuladores para eventos do mouse e nos permitirá arrastar o item de conteúdo do delegado. Ele também atua como um contêiner para o item de conteúdo, o que é importante, pois o item raiz de um delegado é posicionado pela visualização e não pode ser movido por outros meios.

        MouseArea {
            id: dragArea

            property bool held: false
            required property string name
            required property string type
            required property string size
            required property int age

            anchors {
                left: parent?.left
                right: parent?.right
            }
            height: content.height

            drag.target: held ? content : undefined
            drag.axis: Drag.YAxis

            onPressAndHold: held = true
            onReleased: held = false

            Rectangle {
                id: content
            }
        }

O arrastamento do item de conteúdo é habilitado ao vinculá-lo à propriedade ` drag.target ` do ` MouseArea`. Como ainda queremos que a visualização possa ser percorrida com um movimento rápido, esperamos até que o sinal ` pressAndHold ` do ` MouseArea` seja emitido antes de vincular o alvo de arrastamento. Dessa forma, quando o mouse se move antes que o tempo limite de espera expire, isso é interpretado como um movimento da lista; se ele se mover depois disso, é interpretado como o arrastamento de um item. Para deixar mais claro para o usuário quando um item pode ser arrastado, vamos alterar a cor de fundo do item de conteúdo quando o tempo limite expirar.

                color: dragArea.held ? "lightsteelblue" : "white"
                Behavior on color { ColorAnimation { duration: 100 } }

Outra coisa que precisamos fazer antes que um item possa ser arrastado é desativar quaisquer âncoras no item de conteúdo para que ele possa ser movido livremente. Fazemos isso em uma mudança de estado que é acionada quando o item delegado é mantido pressionado; ao mesmo tempo, podemos reatribuir o item de conteúdo ao item raiz, para que ele fique acima dos outros itens na ordem de empilhamento e não seja obscurecido enquanto é arrastado.

                states: State {
                    when: dragArea.held

                    ParentChange {
                        target: content
                        parent: root
                    }
                    AnchorChanges {
                        target: content
                        anchors {
                            horizontalCenter: undefined
                            verticalCenter: undefined
                        }
                    }
                }

Projeto de exemplo em @code.qt.io

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