Nesta página

Animações

Qt Quick oferece a capacidade de animar propriedades. A animação de propriedades permite que os valores das propriedades passem por valores intermediários, em vez de mudarem imediatamente para o valor de destino. Para animar a posição de um item, você pode animar as propriedades que controlam a posição do item, como x e y, por exemplo, de modo que a posição do item mude a cada quadro até chegar à posição de destino.

Interfaces de usuário fluidas

O QML foi projetado para facilitar a criação de interfaces de usuário fluidas. Trata-se de interfaces de usuário nas quais os componentes se animam, em vez de aparecerem, desaparecerem ou saltarem abruptamente. O ` Qt Quick ` oferece duas maneiras simples de fazer com que os componentes da interface de usuário se movam com animação, em vez de aparecerem instantaneamente em seu novo local.

Estados e transições

Qt Quick permite que você declare vários estados de interface do usuário em objetos ` State `. Esses estados são compostos por alterações de propriedades a partir de um estado base e podem ser uma forma útil de organizar sua lógica de interface do usuário. Transições são objetos que você pode associar a um item para definir como suas propriedades serão animadas quando mudarem devido a uma mudança de estado.

Os estados e transições de um item podem ser declarados com as propriedades ` Item::states ` e ` Item::transitions `. Os estados são declarados dentro da propriedade `states list` de um item, geralmente o item raiz do componente. As transições definidas no mesmo item são usadas para animar as mudanças no estado. Veja um exemplo.

Item {
    id: container
    width: 320
    height: 120

    Rectangle {
        id: rect
        color: "red"
        width: 120
        height: 120

        TapHandler {
            onTapped: container.state === '' ? container.state = 'other' : container.state = ''
        }
    }
    states: [
        // This adds a second state to the container where the rectangle is farther to the right

        State { name: "other"

            PropertyChanges {
                target: rect
                x: 200
            }
        }
    ]
    transitions: [
        // This adds a transition that defaults to applying to all state changes

        Transition {

            // This applies a default NumberAnimation to any changes a state change makes to x or y properties
            NumberAnimation { properties: "x,y" }
        }
    ]
}

Animação de alterações de propriedades.

Os comportamentos podem ser usados para especificar uma animação a ser aplicada a uma propriedade quando ela mudar. Essa animação é então aplicada a todas as alterações, independentemente de sua origem. O exemplo a seguir anima um botão se movendo pela tela usando comportamentos.

Item {
    width: 320
    height: 120

    Rectangle {
        color: "green"
        width: 120
        height: 120

        // This is the behavior, and it applies a NumberAnimation to any attempt to set the x property
        Behavior on x {

            NumberAnimation {
                //This specifies how long the animation takes
                duration: 600
                //This selects an easing curve to interpolate with, the default is Easing.Linear
                easing.type: Easing.OutBounce
            }
        }

        TapHandler {
            onTapped: parent.x == 0 ? parent.x = 200 : parent.x = 0
        }
    }
}

Outras animações

Nem todas as animações precisam estar vinculadas a uma propriedade ou estado específico. Você também pode criar animações de forma mais geral e especificar itens e propriedades de destino dentro da animação. Aqui estão alguns exemplos de diferentes maneiras de fazer isso:

Item {
    width: 320
    height: 120

    Rectangle {
        color: "blue"
        width: 120
        height: 120

        // By setting this SequentialAnimation on x, it and animations within it will automatically animate
        // the x property of this element
        SequentialAnimation on x {
            id: xAnim
            // Animations on properties start running by default
            running: false
            loops: Animation.Infinite // The animation is set to loop indefinitely
            NumberAnimation { from: 0; to: 200; duration: 500; easing.type: Easing.InOutQuad }
            NumberAnimation { from: 200; to: 0; duration: 500; easing.type: Easing.InOutQuad }
            PauseAnimation { duration: 250 } // This puts a bit of time between the loop
        }

        TapHandler {
            // The animation starts running when you click within the rectangle
            onTapped: xAnim.running = true
        }
    }
}
Item {
    width: 320
    height: 120

    Rectangle {
        id: rectangle
        color: "yellow"
        width: 120
        height: 120

        TapHandler {
            // The animation starts running when you click within the rectangle
            onTapped: anim.running = true;
        }
    }

    // This animation specifically targets the Rectangle's properties to animate
    SequentialAnimation {
        id: anim
        // Animations on their own are not running by default
        // The default number of loops is one, restart the animation to see it again

        NumberAnimation { target: rectangle; property: "x"; from: 0; to: 200; duration: 500 }

        NumberAnimation { target: rectangle; property: "x"; from: 200; to: 0; duration: 500 }
    }
}

Quadrados vermelhos, verdes, azuis e amarelos dispostos de forma escalonada

Mais informações sobre animações podem ser encontradas na página Conceitos importantes no Qt Quick — Estados, transições e animações.

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