SlideShare una empresa de Scribd logo
1 de 70
Descargar para leer sin conexión
Qt Quick – GUI programming with QML
            SERIOUS ABOUT SOFTWARE
Timo Strömmer, Jan 4, 2011
                                      1
Previous day quick quizz
 •   What are the ways to lay out items?

 •   What is the purpose of id property

 •   Which colors are visible in following:




                                              2
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
Contents – Day 2
 •   Adding data to GUI
      • Data models
      • Views
      • Delegates




                          4
Component and script files, dynamic object loading

STRUCTURING QML
PROGRAMS

                                                     5
QML components
 •    Refresher from yesterday




       FunWithQML
     extends Rectancle




                                 6
Component files
 •   The import statement can be used to
     reference QML files in other directories

      • Single file import

      • Directory import



 •   Imported directory can be scoped




                                                7
Script files
 •   The import statement also works with
     JavaScript

      • Can import files, not directories

      • Must have the as qualifier




                                            8
Property scopes
 •   Properties of components are visible to
     child components

      • But, considered bad practice
                                   RedRect.qml
      Main.qml




                                                 9
Property scopes
 •   Instead, each component should provide
     an API of it’s own




                                              10
Script scopes
 •   Same scoping rules apply to scripts in
     external 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
JavaScript scoping
 •   If script function declares variables with
     same name, the script variable is used



                                  getText uses local variable
                                    run uses inherited one




                                                                12
Inline components
 •   Components can be declared inline

      • Component element

      • Useful for small or private components
           • For example data model delegates

      • Loader can be used to create instances
           • Loader inherits Item

           • Can be used to load components from web


 •   Example in ComponentLoader directory



                                                       13
Dynamic loading
 •   In addition to Loader, components can be
     loaded dynamically via script code

      • Qt.createComponent loads a Component
           • File or URL as parameter

      • component.createObject creates an instance of
        the loaded component

           • Parent object as parameter

      • Qt.createQmlObject can be used to create QML
        objects from arbitrary string data


 •   Example in ScriptComponents directory

                                                        14
Overview of QML animations

BUILDING FLUID GUI


                             15
Animations overview
 •   Animation changes a property gradually
     over a time period

      • Brings the ”fluidness” into the UI

 •   Different types for different scenarios

 •   Supports grouping and nesting




                                               16
Animation basics
 •   All animations inherit from Animation base
     component

      • 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
Animation types
 •   Property value sources

 •   Behavioral

 •   Standalone

 •   Signal handlers

 •   State transitions




                              18
Animation types
 •   Property value source animation is run as
     soon as the target object is created

      • Animation provides the property value

      • Animation on Property syntax
           • Starts at from or current value

           • Ends at to

           • Lasts duration milliseconds




                                                 19
Animation types
 •   Behavioral animation

      • Default animation that is run when property
         changes

      • Behavior on Property syntax




      • No from or to needed, since old and new values
         come from the property change


                                                         20
Animation types
 •   Standalone animations are created as any
     other QML object

      • Attached to target object
            • Affects a property or properties

            • from optional, to mandatory

      • Need to be explicitly started




                                                 21
Animation types
 •   Signal handler animation is quite similar to
     standalone animation

      • Start is triggered by the signal

      • Otherwise same rules
            • Needs to be bound to target and property

            • from optional, to mandatory




 •   More about state transitions in later slides


                                                         22
Animation types
 •   Example code in AnimationExamples
     directory

      • Uses NumberAnimation for various scenarios




                                                     23
Animation objects
 •   The actual animation is built from
     animation objects

      • PropertyAnimation and it’s derivatives
            • NumberAnimation, SmoothedAnimation,
              ColorAnimation, RotationAnimation, SpringAnimation

      • Grouping and nesting
            • SequentialAnimation, ParallelAnimation,
              PauseAnimation

      • GUI layout changes
            • AnchorAnimation, ParentAnimation



                                                                   24
Animation grouping
 •   Animations can be grouped to build more
     complex 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
Animation grouping
 •   Sequential and parallel animations can be
     nested

      • For example, a parallel animation may contain
         multiple sequential animations


 •   Example in AnimationGrouping directory

      • Also uses ColorAnimation




                                                        26
GUI states and animated state transitions

BUILDING FLUID GUI


                                            27
GUI states
 •   A state represents a snapshot of a GUI
                  Click on
                   ”Edit”




                     Mouse on
                     file name


                                              28
GUI states
 •   States are usually applicable at many
     levels, 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
GUI states in QML
 •   State framework built into QML:

      • Every GUI Item has a state property, default
         state and a list of states

            • 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 another
         state instead of the default

            • extend property



                                                                   30
GUI states
 •   Only one state is active at a time

      • So, only properties from default and changes
         from active state are in use

      • State can be activated via script or with the help
         of when binding


 •   Example in SimpleState directory




                                                             31
State transitions
 •   The transitions between states are declared
     separately from the states

      • List of transitions under the Item

      • Quite similar to ParallelAnimation
            • Although, doesn’t inherit Animation


 •   Example in SimpleStateTransition directory




                                                    32
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 <property>

 •   Transition animations are run in parallel

      • Can be wrapped into SequentialAnimation

      • Transition reversible flag might be needed
            • Runs sequential animations in reverse order




                                                            33
State examples
 •   SequentialTransition directory

      • Transitions quizz

 •   Mapping the AnimationGrouping example
     into state framework

      • StateExample directory




                                             34
Advanced animation topics

BUILDING FLUID GUI


                            35
Layout animations
 •   The anchors of GUI Items can be changed
     while 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 in AnchorAnimations directory


                                                           36
Layout animations
 •   In addition to anchor changes, the parent-
     child relationship of items can be changed

      • ParentChange element within a state
           • Changes the parent of an item

           • Optionally also the coordinates, size and transform

      • New relative coordinates

      • Requires re-anchoring within new parent

 •   Example in ParentChange directory



                                                                   37
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 velocity instead of duration
            • So speed doesn’t depend on distance moved

      • Easing curve built in

                                                          38
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
Easing curves
 •   Property and anchor animations may have
     an easing curve

      • Results in non-linear property change

      • Quite a lot of pre-defined curves
            • Check PropertyAnimation.easing.type for details


 •   Quick task:

      • Open AnimationGrouping example and add
         some easing curves




                                                                40
Script hooks
 •   StateChangeScript is run when a state is
     entered

      • Before state transitions are run

 •   ScriptAction within SequentialAnimation
                                                   Also, don’t forget
      • Can relocate a StateChangeScript call    on<Property>Changed
                                                hook from first day slides




                                                                         41
Animation actions
 •   ScriptAction can also run without states

      • Use script property instead of scriptName




 •   PropertyAction changes a property without
     performing animations

      • For example bool flags, z-value etc.




                                                    42
Animation notes
 •   Transformations (especially rotation) may
     produce 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




                                              See also ClockExample



                                                                      43
Handling mouse and keyboard input

USER INTERACTION


                                    44
Mouse and key events
 •   Mouse and keys are handled via events

      • MouseEvent contains position and button
         combination

            • Posted to Item under cursor

      • KeyEvent contains key that was pressed
            • Posted to Item, which has the active focus

      • If item doesn’t handle it, event goes to parent
            • When accepted properties is set to true, the event
              propagation will stop

      • Events are signal parameters


                                                                   45
Mouse input
 •   MouseArea element has already been used
     in most of the examples

      • Works for desktop and mobile devices
            • Although, some signals will not be portable

      • pressed property
            • Any mouse button (pressedButtons for filtering)

            • Finger-press on touch screen

      • Position of events:
            • mouseX and mouseY properties

            • mouse signal parameter


                                                                46
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
Keyboard input
 •   Each Item supports keyboard input

      • Keys and KeyNavigation attached properties
            • Keys.on<Key>Pressed signals

            • KeyNavigation.up / down / left / right properties

      • 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
Keyboard input
 •   FocusScope element can create focus
     groups

      • 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
Flickable element
 •   Scrollable container for other elements

      • Drag or flick to scroll

      • Scrollbars not built-in
            • ScrollBar example available in QML documentation



        contentWidth

           height
             width


                     contentHeight

                                                                 50
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 and pressDelay properties

 •   Example in FlickableExample directory

      • Also contains StateChangeScript and
         PropertyAction examples




                                                            51
Flipable element
 •   Flipable is a two-sided container

      • Card with front and back items

      • Must use Rotation transform to see the back
           • Either via x or y axis, z won’t 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
Models, views and delegates

DISPLAYING DATA


                              53
Data elements
 •   Data elements are divided into three parts

      • Model contains the data
            • Each data element has a role

      • View defines the layout for the data elements
            • Pre-defined views: ListView, GridView and PathView

      • Delegate displays a single model element
            • Any Item-based component works




                                                                   54
Data models
 •   ListModel for list of data elements

      • Define ListElement objects in QML code
           • ListElement consists of roles, not properties

           • 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
Data models
 •   ListModel is manipulated via script code

      • append, insert, move, remove, clear

      • get, set, setProperty

      • Changes to model are automatically reflected in
         the view(s) which display the model

            • Although, changes via WorkerScript need sync


 •   Example in SimpleDataModel directory




                                                             56
Data models
 •   Other model types

      • XmlListModel for mapping XML-data (for
        example from web services) into QML view

           • Uses XPath queries within list elements (XmlRole)

      • FolderListModel from QtLabs experimental
           • Displays local file system contents

      • VisualItemModel for GUI Items

      • VisualDataModel
           • Can visualize Qt/C++ tree models

           • May share GUI delegates across views


                                                                 57
Data views
 •   QML has three views

      • ListView displays it’s contents in a list
            • Each element gets a row or column of its own

            • Compare to Row or Column positioners

      • GridView is two-dimensional representation
            • Compare with Grid positioner

      • PathView can be used to build 2-dimensional
         paths where elements travel




                                                             58
Path view
 •   The PathView component declares a path
     on which the model elements travel

      • Path consists of path segments
           • PathLine, PathQuad, PathCubic          (10,10)             (110,10)

           • Start and end point + control points

      • Each segment may have path attributes
                                                              (60,80)
           • Interpolated values forwarded to delegate


 •   Example in PhotoExample directory



                                                                                   59
Data view notes
 •   Note the lack of tree view

      • Probably not good for small screens

 •   Repeater was used in earlier example

      • Not a view, but can work with model and
         delegate

           • Or directly with GUI Items




                                                  60
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
GUI delegates
 •   A delegate component maps a model entry
     into a GUI Item

      • In VisualItemModel each entry is GUI item

 •   Delegate objects are created and destroyed
     by the view as needed

      • Saves resources with lots of items
            • Remember dynamic object management slides at
              beginning of this day

      • Cannot be used to store any state


                                                             62
GUI delegates
 •   The delegate may access the list model
     roles by name

      • If role name is ambiguous, use model attached
         property

      • Special index role also available

 •   See delegate code examples from
     SimpleDataModel and PhotoExample




                                                        63
View selection
 •   Each view has currentIndex property

      • ListView and GridView have currentItem

      • Represents the selected element

 •   View has highlight delegate

      • Draws something under the current item

      • Highlight moves with SmoothedAnimation
           • Can be customized with highlightFollowsCurrentItem


 •   Example in ViewHighlight directory

                                                                  64
Adding states and transitions

FLUID GUI EXERCISES


                                65
States and transitions
 •   Replace one of the original colors with a
     button, which flips the color list over and
     reveals more colors




                                                   66
States and transitions
 •   Add an area to left side, which slides in
     when mouse is clicked on it

      • Slides back when clicked again




                                                 67
Implementing a model and view

DATA MODEL EXERCISE


                                68
Data model exercise
 •   Add a ListModel to the central
     area 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
70

Más contenido relacionado

La actualidad más candente

Qt for beginners part 2 widgets
Qt for beginners part 2   widgetsQt for beginners part 2   widgets
Qt for beginners part 2 widgetsICS
 
Qt and the Red Flag Linux Distro
Qt and the Red Flag Linux DistroQt and the Red Flag Linux Distro
Qt and the Red Flag Linux Distroaccount inactive
 
Optimizing Performance in Qt-Based Applications
Optimizing Performance in Qt-Based ApplicationsOptimizing Performance in Qt-Based Applications
Optimizing Performance in Qt-Based Applicationsaccount inactive
 
Introduction to QtWebKit
Introduction to QtWebKitIntroduction to QtWebKit
Introduction to QtWebKitAriya Hidayat
 
Deltacloud Presentation - OSSConf 2010
Deltacloud Presentation - OSSConf 2010Deltacloud Presentation - OSSConf 2010
Deltacloud Presentation - OSSConf 2010Michal Fojtik
 
Developments in the Qt WebKit Integration
Developments in the Qt WebKit IntegrationDevelopments in the Qt WebKit Integration
Developments in the Qt WebKit Integrationaccount inactive
 
How to Make Your Qt App Look Native
How to Make Your Qt App Look NativeHow to Make Your Qt App Look Native
How to Make Your Qt App Look Nativeaccount inactive
 
Kubernetes Overview - Deploy your app with confidence
Kubernetes Overview - Deploy your app with confidenceKubernetes Overview - Deploy your app with confidence
Kubernetes Overview - Deploy your app with confidenceOmer Barel
 
Testing Spark and Scala
Testing Spark and ScalaTesting Spark and Scala
Testing Spark and Scaladatamantra
 
Kubernetes The New Research Platform
Kubernetes The New Research PlatformKubernetes The New Research Platform
Kubernetes The New Research PlatformBob Killen
 
Angry Developer: Creating a Game in QML and JavaScript for MeeGo N9 @iRajLal
Angry Developer: Creating a Game in QML and JavaScript for MeeGo N9 @iRajLalAngry Developer: Creating a Game in QML and JavaScript for MeeGo N9 @iRajLal
Angry Developer: Creating a Game in QML and JavaScript for MeeGo N9 @iRajLalRaj Lal
 
GStreamer support in WebKit. what’s new?
GStreamer support in WebKit. what’s new?GStreamer support in WebKit. what’s new?
GStreamer support in WebKit. what’s new?philn2
 
Smashing the bottleneck: Qt application profiling
Smashing the bottleneck: Qt application profilingSmashing the bottleneck: Qt application profiling
Smashing the bottleneck: Qt application profilingDeveler S.r.l.
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QMLAlan Uthoff
 
Development with Qt for Windows CE
Development with Qt for Windows CEDevelopment with Qt for Windows CE
Development with Qt for Windows CEaccount inactive
 
CD, docker and kubernetes
CD, docker and  kubernetesCD, docker and  kubernetes
CD, docker and kubernetesMartin Podval
 

La actualidad más candente (20)

Qt for beginners part 2 widgets
Qt for beginners part 2   widgetsQt for beginners part 2   widgets
Qt for beginners part 2 widgets
 
Qt and the Red Flag Linux Distro
Qt and the Red Flag Linux DistroQt and the Red Flag Linux Distro
Qt and the Red Flag Linux Distro
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
 
Optimizing Performance in Qt-Based Applications
Optimizing Performance in Qt-Based ApplicationsOptimizing Performance in Qt-Based Applications
Optimizing Performance in Qt-Based Applications
 
Turbo charging v8 engine
Turbo charging v8 engineTurbo charging v8 engine
Turbo charging v8 engine
 
Introduction to QtWebKit
Introduction to QtWebKitIntroduction to QtWebKit
Introduction to QtWebKit
 
OSGi Cloud Ecosystems
OSGi Cloud EcosystemsOSGi Cloud Ecosystems
OSGi Cloud Ecosystems
 
Deltacloud API
Deltacloud APIDeltacloud API
Deltacloud API
 
Deltacloud Presentation - OSSConf 2010
Deltacloud Presentation - OSSConf 2010Deltacloud Presentation - OSSConf 2010
Deltacloud Presentation - OSSConf 2010
 
Developments in the Qt WebKit Integration
Developments in the Qt WebKit IntegrationDevelopments in the Qt WebKit Integration
Developments in the Qt WebKit Integration
 
How to Make Your Qt App Look Native
How to Make Your Qt App Look NativeHow to Make Your Qt App Look Native
How to Make Your Qt App Look Native
 
Kubernetes Overview - Deploy your app with confidence
Kubernetes Overview - Deploy your app with confidenceKubernetes Overview - Deploy your app with confidence
Kubernetes Overview - Deploy your app with confidence
 
Testing Spark and Scala
Testing Spark and ScalaTesting Spark and Scala
Testing Spark and Scala
 
Kubernetes The New Research Platform
Kubernetes The New Research PlatformKubernetes The New Research Platform
Kubernetes The New Research Platform
 
Angry Developer: Creating a Game in QML and JavaScript for MeeGo N9 @iRajLal
Angry Developer: Creating a Game in QML and JavaScript for MeeGo N9 @iRajLalAngry Developer: Creating a Game in QML and JavaScript for MeeGo N9 @iRajLal
Angry Developer: Creating a Game in QML and JavaScript for MeeGo N9 @iRajLal
 
GStreamer support in WebKit. what’s new?
GStreamer support in WebKit. what’s new?GStreamer support in WebKit. what’s new?
GStreamer support in WebKit. what’s new?
 
Smashing the bottleneck: Qt application profiling
Smashing the bottleneck: Qt application profilingSmashing the bottleneck: Qt application profiling
Smashing the bottleneck: Qt application profiling
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
Development with Qt for Windows CE
Development with Qt for Windows CEDevelopment with Qt for Windows CE
Development with Qt for Windows CE
 
CD, docker and kubernetes
CD, docker and  kubernetesCD, docker and  kubernetes
CD, docker and kubernetes
 

Destacado

Learn how to develop applications and UIs with Qt Commercial
Learn how to develop applications and UIs with Qt CommercialLearn how to develop applications and UIs with Qt Commercial
Learn how to develop applications and UIs with Qt CommercialQt Commercial, Digia
 
Fun with QML and JavaScript: Embedded Linux Conference 11th April 2011, Hotel...
Fun with QML and JavaScript: Embedded Linux Conference 11th April 2011, Hotel...Fun with QML and JavaScript: Embedded Linux Conference 11th April 2011, Hotel...
Fun with QML and JavaScript: Embedded Linux Conference 11th April 2011, Hotel...Raj Lal
 
QML demo for makerpro (1)
QML demo for makerpro (1)QML demo for makerpro (1)
QML demo for makerpro (1)diro fan
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...Raj Lal
 
Mobile Operating Systems
Mobile Operating SystemsMobile Operating Systems
Mobile Operating SystemsAndreas Jakl
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickICS
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVICS
 
Developing Driver Terminal for Forage Harvester with QML and Qt
Developing Driver Terminal for Forage Harvester with QML and QtDeveloping Driver Terminal for Forage Harvester with QML and Qt
Developing Driver Terminal for Forage Harvester with QML and QtBurkhard Stubert
 
Practical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme ChangePractical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme ChangeBurkhard Stubert
 

Destacado (12)

QtQuick Day 3
QtQuick Day 3QtQuick Day 3
QtQuick Day 3
 
Learn how to develop applications and UIs with Qt Commercial
Learn how to develop applications and UIs with Qt CommercialLearn how to develop applications and UIs with Qt Commercial
Learn how to develop applications and UIs with Qt Commercial
 
Fun with QML and JavaScript: Embedded Linux Conference 11th April 2011, Hotel...
Fun with QML and JavaScript: Embedded Linux Conference 11th April 2011, Hotel...Fun with QML and JavaScript: Embedded Linux Conference 11th April 2011, Hotel...
Fun with QML and JavaScript: Embedded Linux Conference 11th April 2011, Hotel...
 
QML demo for makerpro (1)
QML demo for makerpro (1)QML demo for makerpro (1)
QML demo for makerpro (1)
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
 
Mobile Operating Systems
Mobile Operating SystemsMobile Operating Systems
Mobile Operating Systems
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt Quick
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IV
 
Developing Driver Terminal for Forage Harvester with QML and Qt
Developing Driver Terminal for Forage Harvester with QML and QtDeveloping Driver Terminal for Forage Harvester with QML and Qt
Developing Driver Terminal for Forage Harvester with QML and Qt
 
Practical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme ChangePractical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme Change
 

Similar a QtQuick Day 2

Qt State Machine Framework
Qt State Machine FrameworkQt State Machine Framework
Qt State Machine Frameworkaccount inactive
 
Animation Framework: A Step Towards Modern UIs
Animation Framework: A Step Towards Modern UIsAnimation Framework: A Step Towards Modern UIs
Animation Framework: A Step Towards Modern UIsaccount inactive
 
Surviving a Plane Crash, a NU.nl case-study
Surviving a Plane Crash, a NU.nl case-studySurviving a Plane Crash, a NU.nl case-study
Surviving a Plane Crash, a NU.nl case-studypeter_ibuildings
 
Specifying the behaviour of building automation systems
Specifying the behaviour of building automation systemsSpecifying the behaviour of building automation systems
Specifying the behaviour of building automation systemsJoão Aguiam
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Alan Christensen
 
JBCNConf: jBPM & Vert.x Reactive and Polyglot BPM
JBCNConf: jBPM & Vert.x Reactive and Polyglot BPMJBCNConf: jBPM & Vert.x Reactive and Polyglot BPM
JBCNConf: jBPM & Vert.x Reactive and Polyglot BPMMauricio (Salaboy) Salatino
 
Introduction of openGL
Introduction  of openGLIntroduction  of openGL
Introduction of openGLGary Yeh
 
Get your Project back in Shape!
Get your Project back in Shape!Get your Project back in Shape!
Get your Project back in Shape!Joachim Tuchel
 
Hsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfHsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfAAFREEN SHAIKH
 
Deploying microservices on AWS
Deploying microservices on AWSDeploying microservices on AWS
Deploying microservices on AWSMichael Haberman
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And ComponentsDaniel Fagnan
 
Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native CompilerSimon Ritter
 

Similar a QtQuick Day 2 (20)

Qt State Machine Framework
Qt State Machine FrameworkQt State Machine Framework
Qt State Machine Framework
 
Libreplan architecture
Libreplan architectureLibreplan architecture
Libreplan architecture
 
AngularJS
AngularJSAngularJS
AngularJS
 
InfectNet Technical
InfectNet TechnicalInfectNet Technical
InfectNet Technical
 
JavaFX 101
JavaFX 101JavaFX 101
JavaFX 101
 
Animation Framework: A Step Towards Modern UIs
Animation Framework: A Step Towards Modern UIsAnimation Framework: A Step Towards Modern UIs
Animation Framework: A Step Towards Modern UIs
 
Surviving a Plane Crash, a NU.nl case-study
Surviving a Plane Crash, a NU.nl case-studySurviving a Plane Crash, a NU.nl case-study
Surviving a Plane Crash, a NU.nl case-study
 
Specifying the behaviour of building automation systems
Specifying the behaviour of building automation systemsSpecifying the behaviour of building automation systems
Specifying the behaviour of building automation systems
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated
 
JBCNConf: jBPM & Vert.x Reactive and Polyglot BPM
JBCNConf: jBPM & Vert.x Reactive and Polyglot BPMJBCNConf: jBPM & Vert.x Reactive and Polyglot BPM
JBCNConf: jBPM & Vert.x Reactive and Polyglot BPM
 
Introduction of openGL
Introduction  of openGLIntroduction  of openGL
Introduction of openGL
 
Get your Project back in Shape!
Get your Project back in Shape!Get your Project back in Shape!
Get your Project back in Shape!
 
Intro to Kubernetes
Intro to KubernetesIntro to Kubernetes
Intro to Kubernetes
 
xaml overview
xaml overviewxaml overview
xaml overview
 
Hsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfHsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdf
 
Deploying microservices on AWS
Deploying microservices on AWSDeploying microservices on AWS
Deploying microservices on AWS
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And Components
 
The Architect Way
The Architect WayThe Architect Way
The Architect Way
 
Cucumber, Cuke4Duke, and Groovy
Cucumber, Cuke4Duke, and GroovyCucumber, Cuke4Duke, and Groovy
Cucumber, Cuke4Duke, and Groovy
 
Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native Compiler
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

QtQuick Day 2

  • 1. Qt Quick – GUI programming with QML SERIOUS ABOUT SOFTWARE Timo Strömmer, Jan 4, 2011 1
  • 2. Previous day quick quizz • What are the ways to lay out items? • What is the purpose of id property • Which colors are visible in following: 2
  • 3. 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
  • 4. Contents – Day 2 • Adding data to GUI • Data models • Views • Delegates 4
  • 5. Component and script files, dynamic object loading STRUCTURING QML PROGRAMS 5
  • 6. QML components • Refresher from yesterday FunWithQML extends Rectancle 6
  • 7. Component files • The import statement can be used to reference QML files in other directories • Single file import • Directory import • Imported directory can be scoped 7
  • 8. Script files • The import statement also works with JavaScript • Can import files, not directories • Must have the as qualifier 8
  • 9. Property scopes • Properties of components are visible to child components • But, considered bad practice RedRect.qml Main.qml 9
  • 10. Property scopes • Instead, each component should provide an API of it’s own 10
  • 11. Script scopes • Same scoping rules apply to scripts in external 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
  • 12. JavaScript scoping • If script function declares variables with same name, the script variable is used getText uses local variable run uses inherited one 12
  • 13. Inline components • Components can be declared inline • Component element • Useful for small or private components • For example data model delegates • Loader can be used to create instances • Loader inherits Item • Can be used to load components from web • Example in ComponentLoader directory 13
  • 14. Dynamic loading • In addition to Loader, components can be loaded dynamically via script code • Qt.createComponent loads a Component • File or URL as parameter • component.createObject creates an instance of the loaded component • Parent object as parameter • Qt.createQmlObject can be used to create QML objects from arbitrary string data • Example in ScriptComponents directory 14
  • 15. Overview of QML animations BUILDING FLUID GUI 15
  • 16. Animations overview • Animation changes a property gradually over a time period • Brings the ”fluidness” into the UI • Different types for different scenarios • Supports grouping and nesting 16
  • 17. Animation basics • All animations inherit from Animation base component • 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
  • 18. Animation types • Property value sources • Behavioral • Standalone • Signal handlers • State transitions 18
  • 19. Animation types • Property value source animation is run as soon as the target object is created • Animation provides the property value • Animation on Property syntax • Starts at from or current value • Ends at to • Lasts duration milliseconds 19
  • 20. Animation types • Behavioral animation • Default animation that is run when property changes • Behavior on Property syntax • No from or to needed, since old and new values come from the property change 20
  • 21. Animation types • Standalone animations are created as any other QML object • Attached to target object • Affects a property or properties • from optional, to mandatory • Need to be explicitly started 21
  • 22. Animation types • Signal handler animation is quite similar to standalone animation • Start is triggered by the signal • Otherwise same rules • Needs to be bound to target and property • from optional, to mandatory • More about state transitions in later slides 22
  • 23. Animation types • Example code in AnimationExamples directory • Uses NumberAnimation for various scenarios 23
  • 24. Animation objects • The actual animation is built from animation objects • PropertyAnimation and it’s derivatives • NumberAnimation, SmoothedAnimation, ColorAnimation, RotationAnimation, SpringAnimation • Grouping and nesting • SequentialAnimation, ParallelAnimation, PauseAnimation • GUI layout changes • AnchorAnimation, ParentAnimation 24
  • 25. Animation grouping • Animations can be grouped to build more complex 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
  • 26. Animation grouping • Sequential and parallel animations can be nested • For example, a parallel animation may contain multiple sequential animations • Example in AnimationGrouping directory • Also uses ColorAnimation 26
  • 27. GUI states and animated state transitions BUILDING FLUID GUI 27
  • 28. GUI states • A state represents a snapshot of a GUI Click on ”Edit” Mouse on file name 28
  • 29. GUI states • States are usually applicable at many levels, 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
  • 30. GUI states in QML • State framework built into QML: • Every GUI Item has a state property, default state and a list of states • 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 another state instead of the default • extend property 30
  • 31. GUI states • Only one state is active at a time • So, only properties from default and changes from active state are in use • State can be activated via script or with the help of when binding • Example in SimpleState directory 31
  • 32. State transitions • The transitions between states are declared separately from the states • List of transitions under the Item • Quite similar to ParallelAnimation • Although, doesn’t inherit Animation • Example in SimpleStateTransition directory 32
  • 33. 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 <property> • Transition animations are run in parallel • Can be wrapped into SequentialAnimation • Transition reversible flag might be needed • Runs sequential animations in reverse order 33
  • 34. State examples • SequentialTransition directory • Transitions quizz • Mapping the AnimationGrouping example into state framework • StateExample directory 34
  • 36. Layout animations • The anchors of GUI Items can be changed while 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 in AnchorAnimations directory 36
  • 37. Layout animations • In addition to anchor changes, the parent- child relationship of items can be changed • ParentChange element within a state • Changes the parent of an item • Optionally also the coordinates, size and transform • New relative coordinates • Requires re-anchoring within new parent • Example in ParentChange directory 37
  • 38. 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 velocity instead of duration • So speed doesn’t depend on distance moved • Easing curve built in 38
  • 39. 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
  • 40. Easing curves • Property and anchor animations may have an easing curve • Results in non-linear property change • Quite a lot of pre-defined curves • Check PropertyAnimation.easing.type for details • Quick task: • Open AnimationGrouping example and add some easing curves 40
  • 41. Script hooks • StateChangeScript is run when a state is entered • Before state transitions are run • ScriptAction within SequentialAnimation Also, don’t forget • Can relocate a StateChangeScript call on<Property>Changed hook from first day slides 41
  • 42. Animation actions • ScriptAction can also run without states • Use script property instead of scriptName • PropertyAction changes a property without performing animations • For example bool flags, z-value etc. 42
  • 43. Animation notes • Transformations (especially rotation) may produce 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 See also ClockExample 43
  • 44. Handling mouse and keyboard input USER INTERACTION 44
  • 45. Mouse and key events • Mouse and keys are handled via events • MouseEvent contains position and button combination • Posted to Item under cursor • KeyEvent contains key that was pressed • Posted to Item, which has the active focus • If item doesn’t handle it, event goes to parent • When accepted properties is set to true, the event propagation will stop • Events are signal parameters 45
  • 46. Mouse input • MouseArea element has already been used in most of the examples • Works for desktop and mobile devices • Although, some signals will not be portable • pressed property • Any mouse button (pressedButtons for filtering) • Finger-press on touch screen • Position of events: • mouseX and mouseY properties • mouse signal parameter 46
  • 47. 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
  • 48. Keyboard input • Each Item supports keyboard input • Keys and KeyNavigation attached properties • Keys.on<Key>Pressed signals • KeyNavigation.up / down / left / right properties • 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
  • 49. Keyboard input • FocusScope element can create focus groups • 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
  • 50. Flickable element • Scrollable container for other elements • Drag or flick to scroll • Scrollbars not built-in • ScrollBar example available in QML documentation contentWidth height width contentHeight 50
  • 51. 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 and pressDelay properties • Example in FlickableExample directory • Also contains StateChangeScript and PropertyAction examples 51
  • 52. Flipable element • Flipable is a two-sided container • Card with front and back items • Must use Rotation transform to see the back • Either via x or y axis, z won’t 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
  • 53. Models, views and delegates DISPLAYING DATA 53
  • 54. Data elements • Data elements are divided into three parts • Model contains the data • Each data element has a role • View defines the layout for the data elements • Pre-defined views: ListView, GridView and PathView • Delegate displays a single model element • Any Item-based component works 54
  • 55. Data models • ListModel for list of data elements • Define ListElement objects in QML code • ListElement consists of roles, not properties • 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
  • 56. Data models • ListModel is manipulated via script code • append, insert, move, remove, clear • get, set, setProperty • Changes to model are automatically reflected in the view(s) which display the model • Although, changes via WorkerScript need sync • Example in SimpleDataModel directory 56
  • 57. Data models • Other model types • XmlListModel for mapping XML-data (for example from web services) into QML view • Uses XPath queries within list elements (XmlRole) • FolderListModel from QtLabs experimental • Displays local file system contents • VisualItemModel for GUI Items • VisualDataModel • Can visualize Qt/C++ tree models • May share GUI delegates across views 57
  • 58. Data views • QML has three views • ListView displays it’s contents in a list • Each element gets a row or column of its own • Compare to Row or Column positioners • GridView is two-dimensional representation • Compare with Grid positioner • PathView can be used to build 2-dimensional paths where elements travel 58
  • 59. Path view • The PathView component declares a path on which the model elements travel • Path consists of path segments • PathLine, PathQuad, PathCubic (10,10) (110,10) • Start and end point + control points • Each segment may have path attributes (60,80) • Interpolated values forwarded to delegate • Example in PhotoExample directory 59
  • 60. Data view notes • Note the lack of tree view • Probably not good for small screens • Repeater was used in earlier example • Not a view, but can work with model and delegate • Or directly with GUI Items 60
  • 61. 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
  • 62. GUI delegates • A delegate component maps a model entry into a GUI Item • In VisualItemModel each entry is GUI item • Delegate objects are created and destroyed by the view as needed • Saves resources with lots of items • Remember dynamic object management slides at beginning of this day • Cannot be used to store any state 62
  • 63. GUI delegates • The delegate may access the list model roles by name • If role name is ambiguous, use model attached property • Special index role also available • See delegate code examples from SimpleDataModel and PhotoExample 63
  • 64. View selection • Each view has currentIndex property • ListView and GridView have currentItem • Represents the selected element • View has highlight delegate • Draws something under the current item • Highlight moves with SmoothedAnimation • Can be customized with highlightFollowsCurrentItem • Example in ViewHighlight directory 64
  • 65. Adding states and transitions FLUID GUI EXERCISES 65
  • 66. States and transitions • Replace one of the original colors with a button, which flips the color list over and reveals more colors 66
  • 67. States and transitions • Add an area to left side, which slides in when mouse is clicked on it • Slides back when clicked again 67
  • 68. Implementing a model and view DATA MODEL EXERCISE 68
  • 69. Data model exercise • Add a ListModel to the central area 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
  • 70. 70