Download - QtQuick Training Day2
-
7/29/2019 QtQuick Training Day2
1/70
1
SERIOUS ABOUT SOFTWARE
Qt Quick GUI programming with QML
Timo Strmmer, Jan 4, 2011
-
7/29/2019 QtQuick Training Day2
2/70
Previous day quick quizz
What are the ways to lay out items?
What is the purpose ofidproperty
Which colors are visible in following:
2
-
7/29/2019 QtQuick Training Day2
3/70
Contents Day 2
Dynamic object management Inline components
Dynamic loading
Building fluid user interfaces
Animations
States and transitions
User interaction
Mouse and key
Interactive containers
-
7/29/2019 QtQuick Training Day2
4/70
Contents Day 2
Adding data to GUI Data models
Views
Delegates
4
-
7/29/2019 QtQuick Training Day2
5/70
STRUCTURING QMLPROGRAMS
Component and script files, dynamic object loading
5
-
7/29/2019 QtQuick Training Day2
6/70
QML components
Refresher from yesterday
6
FunWithQMLextends Rectancle
-
7/29/2019 QtQuick Training Day2
7/70
Component files
The importstatement can be used toreference QML files in other directories
Single file import
Directory import
Imported directory can be scoped
7
-
7/29/2019 QtQuick Training Day2
8/70
Script files
The importstatement also works withJavaScript
Can import files, not directories
Must have the as qualifier
8
-
7/29/2019 QtQuick Training Day2
9/70
Property scopes
Properties of components are visible tochild components
But, considered bad practice
9
RedRect.qml
Main.qml
-
7/29/2019 QtQuick Training Day2
10/70
Property scopes
Instead, each component should providean API of its own
10
-
7/29/2019 QtQuick Training Day2
11/70
Script scopes
Same scoping rules apply to scripts inexternal JavaScript files
i.e. same as replacing the function call with the
script
Again, not good practice as it makes the
program quite confusing
11
-
7/29/2019 QtQuick Training Day2
12/70
JavaScript scoping
If script function declares variables withsame name, the script variable is used
12
getText uses local variablerun uses inherited one
-
7/29/2019 QtQuick Training Day2
13/70
Inline components
Components can be declared inline
Componentelement
Useful for small or private components
For example data model delegates
Loadercan be used to create instances
Loaderinherits Item
Can be used to load components from web
Example in ComponentLoaderdirectory
13
-
7/29/2019 QtQuick Training Day2
14/70
Dynamic loading
In addition to Loader, components can beloaded dynamically via script code
Qt.createComponentloads a Component
File or URL as parameter
component.createObjectcreates an instance of
the loaded component
Parent object as parameter
Qt.createQmlObjectcan be used to create QML
objects from arbitrary string data
Example in ScriptComponents directory
14
-
7/29/2019 QtQuick Training Day2
15/70
BUILDING FLUID GUI
Overview of QML animations
15
-
7/29/2019 QtQuick Training Day2
16/70
Animations overview
Animation changes a property graduallyover a time period
Brings the fluidness into the UI
Different types for different scenarios
Supports grouping and nesting
16
-
7/29/2019 QtQuick Training Day2
17/70
Animation basics
All animations inherit fromAnimation basecomponent
Basic properties (just like Item for GUI)
Properties for declarative use:
running,paused, loops, alwaysRunToEnd
Can also be used imperatively:
start, stop, pause, resume, restart, complete
17
-
7/29/2019 QtQuick Training Day2
18/70
Animation types
Property value sources
Behavioral
Standalone
Signal handlers
State transitions
18
-
7/29/2019 QtQuick Training Day2
19/70
Animation types
Property value source animation is run assoon as the target object is created
Animation provides the property value
Animation on Propertysyntax
Starts at from or current value
Ends at to
Lasts duration milliseconds
19
-
7/29/2019 QtQuick Training Day2
20/70
Animation types
Behavioralanimation
Default animation that is run when property
changes
Behavior on Propertysyntax
No from or to needed, since old and new values
come from the property change
20
-
7/29/2019 QtQuick Training Day2
21/70
Animation types
Standalone animations are created as anyother QML object
Attached to targetobject
Affects apropertyorproperties
from optional, to mandatory
Need to be explicitly started
21
-
7/29/2019 QtQuick Training Day2
22/70
Animation types
Signal handleranimation is quite similar tostandalone animation
Startis triggered by the signal
Otherwise same rules
Needs to be bound to targetandproperty
from optional, to mandatory
More about state transitions in later slides
22
-
7/29/2019 QtQuick Training Day2
23/70
Animation types
Example code inAnimationExamplesdirectory
Uses NumberAnimation for various scenarios
23
-
7/29/2019 QtQuick Training Day2
24/70
Animation objects
The actual animation is built fromanimation objects
PropertyAnimation and its derivatives
NumberAnimation, SmoothedAnimation,
ColorAnimation, RotationAnimation, SpringAnimation
Grouping and nesting
SequentialAnimation, ParallelAnimation,
PauseAnimation
GUI layout changes
AnchorAnimation, ParentAnimation
24
-
7/29/2019 QtQuick Training Day2
25/70
Animation grouping
Animations can be grouped to build morecomplex scenarios
SequentialAnimation is a list of animations that
is run one at a time
ParallelAnimation is a list of animations that is
run simultaneously
PauseAnimation is used to insert delays into
sequential animations
25
-
7/29/2019 QtQuick Training Day2
26/70
Animation grouping
Sequential and parallel animations can benested
For example, a parallel animation may contain
multiple sequential animations
Example inAnimationGrouping directory
Also uses ColorAnimation
26
-
7/29/2019 QtQuick Training Day2
27/70
BUILDING FLUID GUI
GUI states and animated state transitions
27
-
7/29/2019 QtQuick Training Day2
28/70
GUI states
A state represents a snapshotof a GUI
28
Click onEdit
Mouse onfile name
-
7/29/2019 QtQuick Training Day2
29/70
GUI states
States are usually applicable at manylevels, regardless of problem complexity
i.e. whole program vs. small trinket
Transitions between states
Response to user interaction or other events
Many transitions may be run parallel
May be animated with QML
29
-
7/29/2019 QtQuick Training Day2
30/70
GUI states in QML
State framework built into QML:
Every GUI Item has a state property, default
state and a list ofstates
States are identified by name, default has no name
Each State object inherits properties from
default state and declares the differences
PropertyChanges element
A state may inherit properties from anotherstate instead of the default
extendproperty
30
-
7/29/2019 QtQuick Training Day2
31/70
GUI states
Only one state is active at a time So, only properties from defaultand changes
from active state are in use
State can be activated via script or with the help
ofwhen binding
Example in SimpleState directory
31
-
7/29/2019 QtQuick Training Day2
32/70
State transitions
The transitions between states are declaredseparately from the states
List oftransitions under the Item
Quite similar to ParallelAnimation Although, doesnt inherit Animation
Example in SimpleStateTransition directory
32
-
7/29/2019 QtQuick Training Day2
33/70
State transitions
All transitions are applied by default Can be scoped with from and to
Both are bound to state name
Transition overrides Behavior on
Transition animations are run in parallel
Can be wrapped into SequentialAnimation
Transition reversible flag might be needed
Runs sequential animations in reverse order
33
-
7/29/2019 QtQuick Training Day2
34/70
State examples
SequentialTransition directory Transitions quizz
Mapping theAnimationGrouping example
into state framework
StateExample directory
34
-
7/29/2019 QtQuick Training Day2
35/70
BUILDING FLUID GUI
Advanced animation topics
35
-
7/29/2019 QtQuick Training Day2
36/70
Layout animations
The anchors of GUI Items can be changedwhile application is running
AnchorChanges element within a state
Re-anchors the item to another valid target
AnchorAnimation can be applied to state
transitions list to animate the changes
Animates position and dimensions
Some quirks involved
Example inAnchorAnimations directory
36
-
7/29/2019 QtQuick Training Day2
37/70
Layout animations
In addition to anchor changes, theparent-childrelationship of items can be changed
ParentChange element within a state
Changes theparentof an item
Optionally also the coordinates, size and transform
New relative coordinates
Requires re-anchoring within new parent
Example in ParentChange directory
37
-
7/29/2019 QtQuick Training Day2
38/70
More animation objects
RotationAnimation for angles Configurable rotation direction
Uses shortest path by default
i.e. instead of going back from 359 to 0
SmoothedAnimation for movement
For example translations
Can use velocityinstead ofduration
So speed doesnt depend on distance moved
Easing curve built in
38
-
7/29/2019 QtQuick Training Day2
39/70
More animation objects
SpringAnimation for spring-like movement spring, damping and mass
Some examples in TransformAnimations
directory
Although, note that these animations are not in
any way restricted to transformations
39
-
7/29/2019 QtQuick Training Day2
40/70
Easing curves
Property and anchor animations may havean easing curve
Results in non-linear property change
Quite a lot of pre-defined curves Check PropertyAnimation.easing.type for details
Quick task:
OpenAnimationGrouping example and addsome easing curves
40
-
7/29/2019 QtQuick Training Day2
41/70
Script hooks
StateChangeScriptis run when a state isentered
Before state transitions are run
ScriptAction within SequentialAnimation
Can relocate a StateChangeScriptcall
41
Also, dont forgetonChanged
hook from first day slides
-
7/29/2019 QtQuick Training Day2
42/70
Animation actions
ScriptAction can also run without states Use scriptproperty instead ofscriptName
PropertyAction changes a property withoutperforming animations
For example boolflags, z-value etc.
42
-
7/29/2019 QtQuick Training Day2
43/70
Animation notes
Transformations (especially rotation) mayproduce jagged lines (aliasing)
Each Item has smooth property for anti-aliasing
Smoothing is expensive operation
Might be good idea to try disabling smoothing
for the duration of animations
43
See also ClockExample
-
7/29/2019 QtQuick Training Day2
44/70
USER INTERACTION
Handling mouse and keyboard input
44
-
7/29/2019 QtQuick Training Day2
45/70
Mouse and key events
Mouse and keys are handled via events MouseEventcontains position and button
combination
Posted to Item under cursor
KeyEventcontains key that was pressed
Posted to Item, which has the active focus
If item doesnt handle it, event goes to parent
When acceptedproperties is set to true, the event
propagation will stop
Events are signal parameters
45
-
7/29/2019 QtQuick Training Day2
46/70
Mouse input
MouseArea element has already been usedin most of the examples
Works for desktop and mobile devices
Although, some signals will not be portable
pressedproperty
Any mouse button (pressedButtons for filtering)
Finger-press on touch screen
Position of events:
mouseXand mouseYproperties
mouse signal parameter
46
-
7/29/2019 QtQuick Training Day2
47/70
Mouse drag
MouseArea can make an item draggable Works with mouse and touch
Draggable items may contain children with
mouse handling of their own
The child items must be children of the
MouseArea that declares dragging
MouseArea inherits Item, so may contain child items
drag.filterChildren property
Example in MouseDrag directory
47
-
7/29/2019 QtQuick Training Day2
48/70
Keyboard input
Each Item supports keyboard input Keys and KeyNavigation attached properties
Keys.onPressedsignals
KeyNavigation.up / down / left/ rightproperties
Key events arrive to item with activeFocus
Can be forwarded to other items
Ignored if none of items is focused
Setting focus property to true to get focus
48
-
7/29/2019 QtQuick Training Day2
49/70
Keyboard input
FocusScope element can create focusgroups
Needed for re-usable components
Internals of component are not visible
Invisible item, similarly as MouseArea
One item within each FocusScope may have focus
Item within the FocusScope, which has focus gets key
events
Example in KeyboardFocus directory
49
-
7/29/2019 QtQuick Training Day2
50/70
Flickable element
Scrollable container for other elements Drag or flick to scroll
Scrollbars notbuilt-in
ScrollBar example available in QML documentation
50
height
width
contentWidth
contentHeight
-
7/29/2019 QtQuick Training Day2
51/70
Flickable element
Flickable mouse events Drag events are intercepted by the flickable
Mouse clicks go to children
Similarly as MouseArea with drag enabled
Control via interactive andpressDelayproperties
Example in FlickableExample directory
Also contains StateChangeScriptand
PropertyAction examples
51
-
7/29/2019 QtQuick Training Day2
52/70
Flipable element
Flipable is a two-sided container Card with frontand backitems
Must use Rotation transform to see the back
Either viaxor yaxis,zwont help
Will not go upside-down via x-axis rotation
States and transitions not pre-implemented
Use for example RotationAnimation for transition
Example in FlipExample directory
52
-
7/29/2019 QtQuick Training Day2
53/70
DISPLAYING DATA
Models, views and delegates
53
-
7/29/2019 QtQuick Training Day2
54/70
Data elements
Data elements are divided into three parts Modelcontains the data
Each data element has a role
Viewdefines the layout for the data elements Pre-defined views: ListView, GridViewand PathView
Delegate displays a single model element
Any Item-based component works
54
-
7/29/2019 QtQuick Training Day2
55/70
Data models
ListModelfor list of data elements Define ListElementobjects in QML code
ListElementconsists ofroles, notproperties
Syntax is similar to QML properties (name: value)
But, cannot have scripts or bindings as value
Add JavaScript objects dynamically
Any dictionary-based (name: value) object will work
Works also with nested data structures
55
-
7/29/2019 QtQuick Training Day2
56/70
Data models
ListModelis manipulated via script code append, insert, move, remove, clear
get, set, setProperty
Changes to model are automatically reflected inthe view(s) which display the model
Although, changes via WorkerScriptneed sync
Example in SimpleDataModeldirectory
56
-
7/29/2019 QtQuick Training Day2
57/70
Data models
Other model types XmlListModelfor mapping XML-data (for
example from web services) into QML view
UsesXPath queries within list elements (XmlRole)
FolderListModelfrom QtLabs experimental
Displays local file system contents
VisualItemModelfor GUI Items
VisualDataModel
Can visualize Qt/C++ tree models
May share GUI delegates across views
57
-
7/29/2019 QtQuick Training Day2
58/70
Data views
QML has three views ListViewdisplays its contents in a list
Each element gets a row or column of its own
Compare to Rowor Column positioners
GridViewis two-dimensional representation
Compare with Gridpositioner
PathViewcan be used to build 2-dimensional
paths where elements travel
58
-
7/29/2019 QtQuick Training Day2
59/70
Path view
The PathViewcomponent declares apathon which the model elements travel
Path consists of path segments
PathLine, PathQuad, PathCubic
Start and end point + control points
Each segment may have path attributes
Interpolated values forwarded to delegate
Example in PhotoExample directory
59
(10,10) (110,10)
(60,80)
-
7/29/2019 QtQuick Training Day2
60/70
Data view notes
Note the lack oftree view Probably not good for small screens
Repeaterwas used in earlier example
Not a view, but can work with modeland
delegate
Or directly with GUI Items
60
-
7/29/2019 QtQuick Training Day2
61/70
Data views
Interaction with views List and grid views inherint from Flickable
Content can be scrolled (no scrollbars though)
Path view uses drag and flick to move the items
around the path
Delegates may implement mouse handlers
Same rules as with Flickable nested mouse areas
61
-
7/29/2019 QtQuick Training Day2
62/70
GUI delegates
A delegate component maps a model entryinto a GUI Item
In VisualItemModeleach entry is GUI item
Delegate objects are created and destroyedby the view as needed
Saves resources with lots of items
Remember dynamic object management slides atbeginning of this day
Cannot be used to store any state
62
-
7/29/2019 QtQuick Training Day2
63/70
GUI delegates
The delegate may access the list modelroles by name
If role name is ambiguous, use modelattached
property
Special indexrole also available
See delegate code examples fromSimpleDataModeland PhotoExample
63
-
7/29/2019 QtQuick Training Day2
64/70
View selection
Each view has currentIndexproperty ListViewand GridViewhave currentItem
Represents the selected element
View has highlightdelegate
Draws something underthe current item
Highlight moves with SmoothedAnimation
Can be customized with highlightFollowsCurrentItem
Example in ViewHighlightdirectory
64
-
7/29/2019 QtQuick Training Day2
65/70
FLUID GUI EXERCISES
Adding states and transitions
65
-
7/29/2019 QtQuick Training Day2
66/70
States and transitions
Replace one of the original colors with abutton, which flips the color list over andreveals more colors
66
-
7/29/2019 QtQuick Training Day2
67/70
States and transitions
Add an area to left side, which slides inwhen mouse is clicked on it
Slides back when clicked again
67
-
7/29/2019 QtQuick Training Day2
68/70
DATA MODEL EXERCISE
Implementing a model and view
68
-
7/29/2019 QtQuick Training Day2
69/70
Data model exercise
Add a ListModelto the centralarea of day 1 exercise
Fill with random names
Generator example in
CourseDay2/ListArea.qml
Add selection support to model
When a color on right side is
clicked, tag the name with that
color
Fade-in / fade-out the tag rectangle
69
-
7/29/2019 QtQuick Training Day2
70/70