Инструменты пользователя

Инструменты сайта


develop:qt:quick2

Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
develop:qt:quick2 [2021/08/29 07:43]
admin
develop:qt:quick2 [2021/08/31 15:21] (текущий)
admin
Строка 1: Строка 1:
-====== Qt Quick: Ввод, Анимация, Преставление, С++ ======+====== Qt Quick: Изображения, Ввод, Анимация ======
  
  
Строка 6: Строка 6:
  
 Можно использовать форматы: **JPG**, **PNG** и **SVG**.\\ Можно использовать форматы: **JPG**, **PNG** и **SVG**.\\
 + 
 === Элемент Image === === Элемент Image ===
 Этот элемент отображает файл изображения, указанный в свойстве **source**, файл может находится как локально так и в сети.\\ Этот элемент отображает файл изображения, указанный в свойстве **source**, файл может находится как локально так и в сети.\\
Строка 115: Строка 115:
 </details> </details>
  
 + 
 +=== BorderImage ===
  
-=== BorderImage === 
----- 
 Элемент для нормального масштабирования графики, особенно полезно при закругленных углах (кнопок и т.д.). Элемент разбивает изображение на девять частей.\\ Элемент для нормального масштабирования графики, особенно полезно при закругленных углах (кнопок и т.д.). Элемент разбивает изображение на девять частей.\\
  
Строка 134: Строка 134:
 </details> </details>
  
 + 
 ==== Градиент ==== ==== Градиент ====
 ---- ----
Строка 166: Строка 166:
 </details> </details>
  
 + 
 ==== Рисование Canvas ==== ==== Рисование Canvas ====
 ---- ----
Строка 255: Строка 255:
  
  
 + 
 ===== Пользовательский ввод ===== ===== Пользовательский ввод =====
 ==== Область мыши ==== ==== Область мыши ====
Строка 328: Строка 328:
 </details> </details>
  
 + 
 ==== Сигналы ==== ==== Сигналы ====
 ---- ----
Строка 423: Строка 423:
 </details> </details>
  
 + 
 ==== Ввод с клавиатуры ==== ==== Ввод с клавиатуры ====
 ---- ----
Строка 455: Строка 455:
 </details> </details>
  
 + 
 ==== Фокус ==== ==== Фокус ====
 ---- ----
Строка 461: Строка 461:
 Нетекстовые элементы так же могут иметь фокус.\\ Нетекстовые элементы так же могут иметь фокус.\\
 Для управления порядком фокуса табом, используется т.н. прикрепляемое свойство "**KeyNavigation.tab: <FocusThisElement>**". В этом свойстве так же доступны клавиши типа **KeyNavigation.left**, **KeyNavigation.right**, **KeyNavigation.up**, **KeyNavigation.down** и т.д.\\ Для управления порядком фокуса табом, используется т.н. прикрепляемое свойство "**KeyNavigation.tab: <FocusThisElement>**". В этом свойстве так же доступны клавиши типа **KeyNavigation.left**, **KeyNavigation.right**, **KeyNavigation.up**, **KeyNavigation.down** и т.д.\\
- 
- 
  
 <details> <details>
Строка 507: Строка 505:
 </details> </details>
  
 + 
 ==== Сырой ввод ==== ==== Сырой ввод ====
 ---- ----
Строка 572: Строка 570:
 </details> </details>
  
 + 
 ==== Мультитач ==== ==== Мультитач ====
 ---- ----
Строка 626: Строка 624:
 | x,y | Текущие координаты касания | | x,y | Текущие координаты касания |
  
- + 
 ===== Анимация ===== ===== Анимация =====
 ==== Анимация при изменении свойств ==== ==== Анимация при изменении свойств ====
 ---- ----
 +Для анимации свойств существует элемент **PropertyAnimation**, с ним можно менять сразу **несколько свойств одновременно**.\\
  
 <details> <details>
-<summary>:!: Пример: </summary>+<summary>:!: Пример: Одновременное изменение **x** и **y**</summary>
 <code QML> <code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 400; height: 400; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        color: "lightgreen"
 +        Image
 +        {
 +            id: img
 +            x: 0; y: 0;
 +            source: "qrc:/button.png"
 +        }
 +        PropertyAnimation
 +        {
 +            target: img
 +            properties: "x,y"
 +            // Начальное и конечное значение для св-в
 +            from: 0; to: 400 - img.height
 +            // Длительность мс
 +            duration: 1500
 +            running: true
 +            loops: Animation.Infinite
 +            // Режим. скорость и т.д. есть интерактивный редактор
 +            easing.type: Easing.OutExpo
 +        }
 +    }
 +}
 </code> </code>
 </details> </details>
  
 + 
 +=== Изменение числовых значений ===
 +----
 +Более эффективная реализация для **real** и **int**.\\
  
 +<details>
 +<summary>:!: Пример: Изменение размера вложенного прямоугольника x2</summary>
 +<code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 300; height: 100; visible: true
 +    Rectangle
 +    {
 +        id: par
 +        anchors.fill: parent
 +        color: "lightgreen"
 +        Rectangle
 +        {
 +            x: 0; y: 0;
 +            height: 100
 +            color: "red"
 +            NumberAnimation on width
 +            {
 +                id: anim1
 +                from: 300; to: 0
 +                duration: 2000
 +                easing.type: Easing.InOutCubic
 +                onStopped:
 +                {
 +                    anim2.start()
 +                }
 +            }
  
-====  ==== +            NumberAnimation on width 
-----+            { 
 +                id: anim2 
 +                from: 0; to: 300 
 +                duration: 2000 
 +                easing.type: Easing.InOutCubic 
 +                running: false 
 +                onStopped: 
 +                { 
 +                    anim1.start() 
 +                } 
 +            }
  
 +        }
 +    }
 +}
 +</code>
 +</details>
 +
 + 
 +=== Изменение цвета ===
 +----
 +**ColorAnimation** управляет изменением цвета, так же используется **from** и **to**.\\
  
 <details> <details>
-<summary>:!: Пример: </summary>+<summary>:!: Пример: Изменение цвета</summary>
 <code QML> <code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 300; height: 100; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        ColorAnimation on color
 +        {
 +            from: "lightgreen"
 +            to: "red"
 +            duration: 1500
 +            running: true
 +            loops: Animation.Infinite
 +        }
 +    }
 +}
 </code> </code>
 </details> </details>
  
 + 
 +=== Поворот ===
 +----
 +**RotationAnimation** описывает поворот элемента.\\
 +Его свойство **direction** задает направление поворота:
 +| RotationAnimation.Clockwise | по часовой (по умолчанию) |
 +| RotationAnimation.Counterclockwise | против часовой |
 +| RotationAnimationShortest | угол поворота в наименьшую сторону исходя из "from-to" |
  
 +<details>
 +<summary>:!: Пример: Поворот по часовой стрелке</summary>
 +<code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 150; height: 150; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        Image
 +        {
 +            source: "qrc:/button.png"
 +            anchors.centerIn: parent
 +            smooth: true
 +            RotationAnimation on rotation
 +            {
 +                from: 0
 +                to: 360
 +                duration: 2000
 +                loops: Animation.Infinite
 +                easing.type: Easing.InOutBack
 +            }
 +        }
 +    }
 +}
 +</code>
 +</details>
  
-====  ====+  
 +==== Анимация поведения ====
 ---- ----
 +**Behavior** реагирует на изменение свойств элементов, соответственно в эти моменты может вызывать другую анимацию и т.д.\\ 
 +В следующем примере, **Behavior** реагирует на изменение **x** и **y** у изображения, внутри другой элемент анимации, изменение же свойств изображения вызывается из событиями мыши в **MouseArea**
  
 <details> <details>
-<summary>:!: Пример: </summary>+<summary>:!: Пример: Анимация вызывается поведением </summary>
 <code QML> <code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 360; height: 360; visible: true
 +    Rectangle
 +    {
 +        id: rect
 +        anchors.fill: parent
 +        Image
 +        {
 +            id: img
 +            x: 10; y: 10;
 +            source: "qrc:/button.png"
 +            smooth: true
 +            Text
 +            {
 +                anchors.verticalCenter: img.verticalCenter
 +                anchors.top: img.bottom
 +                text: "Move cursor"
 +            }
 +            Behavior on x
 +            {
 +                NumberAnimation
 +                {
 +                    duration: 500
 +                    easing.type: Easing.OutBack
 +                }
 +            }
 +            Behavior on y
 +            {
 +                NumberAnimation
 +                {
 +                    duration: 500
 +                    easing.type: Easing.OutBack
 +                }
 +            }
 +        }
 +        MouseArea
 +        {
 +            anchors.fill: rect
 +            hoverEnabled: true
 +            onMouseXChanged: img.x= mouseX
 +            onMouseYChanged: img.y= mouseY
 +        }
 +    }
 +}
 </code> </code>
 </details> </details>
  
 + 
 +==== Параллельные и последовательные анимации ====
 +----
 +Анимации могут быть объединены в группы, эти группы выполняются **последовательно** (SequentialAnimation) либо **параллельно** (ParallelAnimation). Группы могут быть вложенными друг в друга. Если элемент группы не указан, анимации выполняются параллельно.\\
  
 +<details>
 +<summary>:!: Пример: Параллельная анимация. Увеличение размера и прозрачность</summary>
 +<code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 360; height: 360; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        Image
 +        {
 +            id: img
 +            source: "qrc:/button.png"
 +            smooth: true
 +            anchors.centerIn: parent
 +        }
 +        ParallelAnimation
 +        {
 +            NumberAnimation
 +            {
 +                target: img
 +                properties: "scale"
 +                from: 0.1
 +                to: 3.0
 +                duration: 2000
 +                easing.type: Easing.InOutCubic
 +            }
 +            NumberAnimation
 +            {
 +                target: img
 +                properties: "opacity"
 +                from: 1.0
 +                to: 0
 +                duration: 2000
 +            }
 +            running: true
 +            loops: Animation.Infinite
 +        }
 +    }
 +}
 +</code>
 +</details>
  
-====  ==== 
----- 
  
 +<details>
 +<summary>:!: Пример: Тоже самое, но немного другой подход </summary>
 +<code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
 +
 +ApplicationWindow
 +{
 +    width: 360; height: 360; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        Image
 +        {
 +            id: img
 +            source: "qrc:/button.png"
 +            smooth: true
 +            anchors.centerIn: parent
 +            NumberAnimation on scale
 +            {
 +                from: 0.1
 +                to: 3.0
 +                duration: 2000
 +                easing.type: Easing.InOutCubic
 +                loops: Animation.Infinite
 +            }
 +            NumberAnimation on opacity
 +            {
 +                from: 1.0
 +                to: 0
 +                duration: 2000
 +                loops: Animation.Infinite
 +            }
 +        }
 +    }
 +}
 +</code>
 +</details>
 +
 +Пример последовательной анимации: После нажатия мыши объект упадет вниз, повернется вокруг своей оси, полежит немного, затем поднимется обратно вверх:
  
 <details> <details>
 <summary>:!: Пример: </summary> <summary>:!: Пример: </summary>
 <code QML> <code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 130; height: 450; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        Image
 +        {
 +            id: img
 +            source: "qrc:/button.png"
 +            smooth: true
 +            Text
 +            {
 +                anchors.horizontalCenter: parent.horizontalAlignment
 +                anchors.top: parent.bottom
 +                text: "Click for do it"
 +            }
 +            MouseArea
 +            {
 +                anchors.fill: img
 +                onClicked: anim.running= true
 +            }
 +            SequentialAnimation
 +            {
 +                id: anim
 +                NumberAnimation
 +                {
 +                    target: img
 +                    from: 20; to: 300;
 +                    properties: "y"
 +                    duration: 1000
 +                    easing.type: Easing.OutBounce
 +                }
 +                RotationAnimation
 +                {
 +                    target: img
 +                    from: 0; to: 360;
 +                    properties: "rotation"
 +                    duration: 1000
 +                }
 +                PauseAnimation {duration: 500}
 +                NumberAnimation
 +                {
 +                    target: img
 +                    from: 300; to: 20;
 +                    properties: "y"
 +                    duration: 1000
 +                    easing.type: Easing.OutBounce
 +                }
 +            }
 +        }
 +    }
 +}
 </code> </code>
 </details> </details>
  
 + 
 +==== Состояния и переходы ====
 +=== Состояния ===
 +----
 +Управлять состоянием можно при помощи элемента **State**, поддерживает наборы списков, описания элементов с набором их состояний.\\
 +Все объекты **обязательно** должны быть **именованными**.\\
 +Список состояний присваивается свойству **states** а необходимый набор присваивается свойству **state**, так и происходит смена состояний.\\
 +Изменение свойств внутри состояния перечисляется в в элементе **PropertyChanges**
  
 +<details>
 +<summary>:!: Пример: Два определенных состояния прямоугольника и смена между ними</summary>
 +<code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 360; height: 360; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
  
 +        Rectangle
 +        {
 +            id: rect
 +            state: "State2"
 +            Text
 +            {
 +                id: txt
 +                anchors.centerIn: parent
 +            }
 +        }
 +        states:
 +        [
 +            State
 +            {
 +                name: "State1"
 +                PropertyChanges
 +                {
 +                    target: rect
 +                    color: "lightgreen"
 +                    width: 150; height: 60;
 +                }
 +                PropertyChanges
 +                {
 +                    target: txt
 +                    text: "State2: Click"
 +                }
 +            },
 +            State
 +            {
 +                name: "State2"
 +                PropertyChanges
 +                {
 +                    target: rect
 +                    color: "yellow"
 +                    width: 200; height: 120;
 +                }
 +                PropertyChanges
 +                {
 +                    target: txt
 +                    text: "State1: Click"
 +                }
 +            }
 +        ]
 +        MouseArea
 +        {
 +            anchors.fill: parent
 +            onClicked: parent.state= (parent.state== "State1") ? "State2":"State1"
 +        }
 +    }
 +}
 +</code>
 +</details>
  
 + 
 +==== Переходы ====
 +----
 +Свойство **transitions** задает список переходов, в списке задаем элементы **Transition**, каждый элемент содержит два момента:
 +  * **from / to** - начальное/конечное состояние перехода (**States**, рассмотренные выше)
 +  * **PropertyAnimation** - управление анимацией перехода
  
 +<details>
 +<summary>:!: Пример: Переход между состояниями</summary>
 +<code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 360; height: 360; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        Rectangle
 +        {
 +            id: rect
 +            width: 100; height: 100
 +            color: "magenta"
 +            state: "State1"
 +            Text
 +            {
 +                anchors.centerIn: parent
 +                text: "Click this"
 +            }
 +            MouseArea
 +            {
 +                anchors.fill: parent
 +                onClicked: rect.state = (rect.state == "State1") ? "State2":"State1"
 +            }
 +            states:
 +            [
 +                State
 +                {
 +                    name: "State1"
 +                    PropertyChanges {target: rect; x: 0; y: 0}
 +                },
 +                State
 +                {
 +                    name: "State2"
 +                    PropertyChanges {target: rect; x: 200; y: 200}
 +                }
 +            ]
 +            transitions:
 +            [
 +                Transition
 +                {
 +                    from: "State1"; to: "State2";
 +                    PropertyAnimation
 +                    {
 +                        target: rect;
 +                        properties: "x,y";
 +                        duration: 1000
 +                        easing.type: Easing.OutBack
 +                    }
 +                },
 +                Transition
 +                {
 +                    from: "State2"; to: "State1";
 +                    PropertyAnimation
 +                    {
 +                        target: rect;
 +                        properties: "x,y";
 +                        duration: 1000
 +                        easing.type: Easing.InBounce
 +                    }
 +                }
 +            ]
 +        }
 +    }
 +}
 +</code>
 +</details>
  
 +Если свойства перехода будут одинаковыми, тогда можно использовать **шаблонный переход**:
  
 +<details>
 +<summary>:!: Пример: Тоже самое только шаблонный переход</summary>
 +<code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2
  
 +ApplicationWindow
 +{
 +    width: 300; height: 300; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        Rectangle
 +        {
 +            id: rect
 +            width: 100; height: 100
 +            color: "magenta"
 +            state: "State1"
 +            Text
 +            {
 +                anchors.centerIn: parent
 +                text: "Click this"
 +            }
 +            MouseArea
 +            {
 +                anchors.fill: parent
 +                onClicked: rect.state = (rect.state == "State1") ? "State2":"State1"
 +            }
 +            states:
 +            [
 +                State
 +                {
 +                    name: "State1"
 +                    PropertyChanges {target: rect; x: 0; y: 0}
 +                },
 +                State
 +                {
 +                    name: "State2"
 +                    PropertyChanges {target: rect; x: 200; y: 200}
 +                }
 +            ]
 +            transitions:
 +            [
 +                Transition
 +                {
 +                    from: "*"; to: "*";
 +                    PropertyAnimation
 +                    {
 +                        target: rect;
 +                        properties: "x,y";
 +                        duration: 1000
 +                        easing.type: Easing.OutBack
 +                    }
 +                }
 +            ]
 +        }
 +    }
 +}
 +</code>
 +</details>
  
 + 
 +==== Модуль частиц ====
 +----
 +Движок для работы с частицами, в роли частиц могут выступать картинки и т.д.
  
 +<details>
 +<summary>:!: Пример: Кнопкопад</summary>
 +<code QML>
 +import QtQuick 2.12; import QtQuick.Controls 2.2; import QtQuick.Particles 2.0
  
 +ApplicationWindow
 +{
 +    width: 360; height: 360; visible: true
 +    Rectangle
 +    {
 +        anchors.fill: parent
 +        color: "MidnightBlue"
 +        ParticleSystem
 +        {
 +            anchors.fill: parent
 +            ImageParticle
 +            {
 +                source: "qrc:/button.png"
 +            }
 +            Emitter
 +            {
 +                width: parent.width
 +                height: parent.height
 +                anchors.bottom: parent.bottom
 +                lifeSpan: 10000
 +                sizeVariation: 16
 +                emitRate: 20
 +                velocity: AngleDirection
 +                {
 +                    angle: 90
 +                    angleVariation: 10
 +                    magnitude: 100
 +                }
 +            }
 +        }
 +    }
 +}
 +</code>
 +</details>
  
develop/qt/quick2.1630222994.txt.gz · Последнее изменение: 2021/08/29 07:43 — admin