Evgenii Legotckoi
Evgenii LegotckoiJan. 4, 2016, 10:41 a.m.

QML - Lesson 022. Animation click on an item in the list Material Design style

QML does not provide animation interactions clicks Material Design Style for Android by default, but is easily adjusted with the Rectangle primitive. Animation is to one parent, Rectangle, when clicked, you need a second child Rectangle object to stretch the entire area of the parent. At the same time the child object will stretch for a certain time and will appear as an expanding circle, but it will not go beyond its parent.

For clarity, create a list of items, which will produce clicks. To track clicks is used area MouseArea, which will be monitored by the interaction of several signals:

  • onClicked - the signal will stop the animation and the result of the interaction performed with the list;
  • onPressed - when the signal is pressing need to run an animation preset coordinates animated object Rectangle.
  • onReleased - you need to stop the animation when you release the list item;
  • onPositionChanged - when you change the position of the field also need to stop the animation.

To make the animation used PropertyAnimation object. This site is chosen goal of animation, and a list of properties that will be subject to change. In the case of animatable object Rectangl, it is necessary to expand the circle, for that increase the properties width, height and radius with the same value. In order to completely fill the parent object properties will exhibit a finite amount three times greater than the width of the parent element.

Another important property is the parent element:

clip - activating this property (true), we cut the child elements of the object, so that they do not go beyond the boundaries of the parent element.


Click Animation - Implementation of the code

import QtQuick 2.5
import QtQuick.Controls 1.4

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    /* Create a list with several items, which will be animated click
     * */
    ListView {
        anchors.fill: parent

        // In the object ...
        delegate: Item {
            height: 48
            anchors.left: parent.left
            anchors.right: parent.right

            // ... rectangular background locates,
            Rectangle {
                id: body
                anchors.fill: parent
                color: "white"
                // child objects will be cut over the area of the parent element
                clip: true

                /* ... which is a different background, which will be animated circle clique
                 * */
                Rectangle {
                    id: colorRect
                    height: 0
                    width: 0
                    color: "#e8e8e8"

                    /* Property transformation, which will be recalculated starting position,
                     * that there was a circle in the center of the click
                     * */
                    transform: Translate {
                        x: -colorRect.width / 2
                        y: -colorRect.height / 2
                    }
                }

                Text {
                    text: fragment
                    anchors.left: parent.left
                    anchors.leftMargin: 72
                    anchors.top: parent.top
                    anchors.bottom: parent.bottom
                    font.pixelSize: 14

                    renderType: Text.NativeRendering
                    horizontalAlignment: Text.AlignLeft
                    verticalAlignment: Text.AlignVCenter
                }

                // Area click on the item
                MouseArea {
                    anchors.fill: parent

                    onClicked: {
                        circleAnimation.stop()
                    }
                    onPressed: {
                        /* When you click on an element exhibiting the starting coordinates 
                         * of the background for the animation range in element
                         * */
                        colorRect.x = mouseX
                        colorRect.y = mouseY
                        // Запускаем анимацию
                        circleAnimation.start()
                    }
                    onReleased: circleAnimation.stop()
                    onPositionChanged: circleAnimation.stop()
                }

                PropertyAnimation {
                    id: circleAnimation
                    target: colorRect   // The aim Asking circular background
                    properties: "width,height,radius" // In animation, change the height, width and radius
                    from: 0             // Change the settings from 0 pixels ...
                    to: body.width*3    // ... to triple the size of the width of the item in the list
                    duration: 300       // within 300 milliseconds

                    // By stopping the animation zero out the height and width of an animated background
                    onStopped: {
                        colorRect.width = 0
                        colorRect.height = 0
                    }
                }
            }
        }
        model: listModel
    }

    ListModel {
        id: listModel

        ListElement {fragment: qsTr("1-й Фрагмент")}
        ListElement {fragment: qsTr("2-й Фрагмент")}
        ListElement {fragment: qsTr("3-й Фрагмент")}
        ListElement {fragment: qsTr("4-й Фрагмент")}
        ListElement {fragment: qsTr("5-й Фрагмент")}
        ListElement {fragment: qsTr("6-й Фрагмент")}
        ListElement {fragment: qsTr("7-й Фрагмент")}
    }
}

Video

Result Material Design animations in the style is not completely identical to what should be, but it shows the basic idea. Demonstration of work you can see in the video tutorial.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • April 1, 2024, 12:29 a.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 4:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 12:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 2:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks