Qt Quick From bottom to top

Similar documents
SERIOUS ABOUT SOFTWARE. Qt Core features. Timo Strömmer, May 26,

Qt Quick Hybrid models

Qt Quick Hybrid models and Mobility

Qt Quick for Qt Developers

Creating Dynamic UIs with Qt Declarative UI

COS2614. Tutorial letter 203/1/2018. Programming: Contemporary Concepts. Semester 1. School of Computing. Discussion of Solutions to Assignment 3

+ C++11. Qt5 with a touch of C++11. Matthew Eshleman covemountainsoftware.com

Qt in Education. Qt Quick

Qt Essentials - Basic Types Module

Rapid Application Development with Qt Quick. Henrik Hartz

Introduction to Programming Using Java (98-388)

Object-Oriented Programming

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Chapter 6 Introduction to Defining Classes

QML for Desktop Applications

The Extensible Markup Language (XML) and Java technology are natural partners in helping developers exchange data and programs across the Internet.

Integrating QML with C++

QT QUICK UI Exam Curriculum

Containers & Iterators

Qt + Maemo development

CERTIFICATE IN WEB PROGRAMMING

CopperSpice: A Pure C++ GUI Library. Barbara Geller & Ansel Sermersheim CPPCon - September 2015

ECE 3574: Dynamic Polymorphism using Inheritance

Tcl/Tk lecture. What is the Wish Interpreter? CIS 410/510 User Interface Programming

CPS 506 Comparative Programming Languages. Programming Language

Compiler Theory. (Semantic Analysis and Run-Time Environments)

Qt Essentials - Model View Module

QUIZ. What is wrong with this code that uses default arguments?

GUI in C++ PV264 Advanced Programming in C++ Nikola Beneš Jan Mrázek Vladimír Štill. Faculty of Informatics, Masaryk University.

Qt Quick for Qt Developers

Introduction to C++11 and its use inside Qt

A deep dive into QML memory management internals

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Applied Type Erasure in Qt 5. Stephen Kelly KDAB

What about Object-Oriented Languages?

Absolute C++ Walter Savitch

Introduction. Part I: jquery API 1. Chapter 1: Introduction to jquery 3

Better UI Makes ugui Better!

And Even More and More C++ Fundamentals of Computer Science

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 5. Names, Bindings, and Scopes

DOT NET Syllabus (6 Months)

Inheritance and Interfaces

What are the characteristics of Object Oriented programming language?

Inheritance, Polymorphism and the Object Memory Model

Exercises Lecture 6 The Graphics View Canvas

1 Lexical Considerations

GUI Components: Part 1

Data Abstraction. Hwansoo Han

P2: Collaborations. CSE 335, Spring 2009

STRUCTURING OF PROGRAM

Get Unique study materials from

User Interface: Layout. Asst. Prof. Dr. Kanda Runapongsa Saikaew Computer Engineering Khon Kaen University

Java Object Oriented Design. CSC207 Fall 2014

Short Notes of CS201

Classes, Objects, and OOP in Java. June 16, 2017

QtQuick Training Course. Module Two

Programming Languages Third Edition. Chapter 7 Basic Semantics

Event Dispatch. Dispatching events to windows and widgets.

D Programming Language

Better UI Makes ugui Better!

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

Interview Questions of C++

The Dynamic Typing Interlude

Visual Web Next Design Concepts. Winston Prakash Feb 12, 2008

Object-Oriented Principles and Practice / C++

10Tec igrid for.net 6.0 What's New in the Release

CS201 - Introduction to Programming Glossary By

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

FilePicker, 123 File transfer, 314. GridListLayout, 192 GroupDataModel, 199

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.)

Pace University. Fundamental Concepts of CS121 1

Comprehensive AngularJS Programming (5 Days)

Subprograms. Copyright 2015 Pearson. All rights reserved. 1-1

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

C# Programming in the.net Framework

COIMBATORE EDUCATIONAL DISTRICT

The basic operations defined on a symbol table include: free to remove all entries and free the storage of a symbol table

Data Structure. Recitation III

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

Qt in Education. The Graphics View Canvas

Lexical Considerations

Chapter 10 :: Data Abstraction and Object Orientation

Self-review Questions

PHP,HTML5, CSS3, JQUERY SYLLABUS

Function names can be specified with winidea syntax for qualified names, if multiple download files and file static functions are tested.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

CSE 307: Principles of Programming Languages

WPF and MVVM Study Guides

! Those values must be stored somewhere! Therefore, variables must somehow be bound. ! How?

Study Guide to Exam 2

Event Dispatch. Interactor Tree Lightweight vs. Heavyweight Positional Dispatch Focus Dispatch. 2.4 Event Dispatch 1

Object-Oriented Programming in C# (VS 2015)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Transcription:

SERIOUS ABOUT SOFTWARE Qt Quick From bottom to top Timo Strömmer, Feb 11, 2011 1

Contents Day 2 Qt core features Shared data objects Object model, signals and slots, properties Hybrid programming QML fluid user interfaces Animations, states and transitions Adding data to GUI Models, views and delegates

Shared data objects CORE FEATURES 3

Shared data objects A shared data object doesn t store the object data by itself Instead, data is implicitly shared With copy-on-write semantics Easier to use that just pointers The object can be thought as simple value type Examples: Strings, images, collections 4

Implicit sharing In normal C++ an object is allocated and a pointer to it is passed around Care must be taken that object is not deleted while it s still being pointed to char *ptr char *ptr H e l l o! \0 char *ptr 5

Implicit sharing In implicit sharing, a reference counter is associated with the data Data pointer is wrapped into a container object, which takes care of deleting the data when reference count reaches 0 QString str Data * QString str Data * Data int ref = 2 H e l l o! \0 6

Implicit sharing Implicitly shared objects can be treated as simple values Only the pointer is passed around QString str Data * QString str Data int ref = 1 Data H e l l o! \0 Data * int ref = 1 C h a n g e \0 7

Terminology Copy-on-write Make a shallow copy until something is changed Shallow copy Copy just the pointer, not actual data Deep copy Create a copy of the data 8

Strings Two types of string UNICODE strings (QString) Byte arrays (QByteArray) In general, QString should be used UNICODE, so can be localized to anything Conversion between the two types is easy, but might have unexpected performance issues 9

Strings and implicit sharing Strings are implicitly shared, so in general, should be treated as a value Returned from functions like value Stored into objects as values Function parameters should use constant reference, not value const QString & 10

String operations In Qt, a string can be changed Thus, differs from java immutable strings Modifying a string in-place is more efficient (especially with reserve() function) However, some care must be taken to avoid changes in unexpected places 11

String operations QString supports various operators +, +=, >, <, <=, >=, ==,!= Also work with literals Character access with [] 12

Generic containers List containers QList, QLinkedList, QVector, QStack, QQueue Usually QList is best for ordinary tasks QStringList for strings Associative containers QSet, QMap, QHash, QMultiMap, QMultiHash QMap for sorted, QHash for unsorted items 13

List containers Lists are index-based, starting from 0 Fast access if index is known, slow to search Adding and removing items append, insert, +=, << Accessing items at, [] 14

Foreach statement Can be used to iterate over lists Takes a shallow copy of the container If original container is modified while in loop, the one used in the loop remains unchanged 15

Associative containers Associative containers are used to map keys to values In QSet, key and value are the same QSet<String> Other containers have separate keys and values QHash<QString,QString> Normal versions have one-to-one mapping, multi-versions accept multiple values for single key QMultiMap<QString, QObject *> 16

Object model CORE FEATURES 17

Object model Usual Qt program is based around a treebased hierarchy of objects Helps with C++ memory management Based on QObject class Do not confuse with class inheritance 18

Object model A QObject may have a parent object and number of child objects QObject Object without parent is called a root object QObject QObject QObject When an object is deleted, it will also delete all it s QObject children 19

Object model and GUI All GUI components inherit from QWidget, which in turn inherits from QObject Thus, GUI widgets are also arranged into tree hierarchy The root widget is a window Enabling / disabling or showing / hiding a widget will also affect its children 20

Signals & slots CORE FEATURES 21

Signals and slots Qt way of making callback functions simple Example cases What happens when user presses a GUI button What happens when data arrives from network Similar semantics as with Java listeners A signal is emitted, which results in a function call to all slots that have been connected to the signal i.e. onsignal: slot() in QML code 22

Signals and slots Code to support signal-slot connections is generated by the moc tool when project is compiled Special keywords are used, which are interpreted by moc Q_OBJECT, signals, slots, emit 23

Special keywords Q_OBJECT keyword must be added to every class that inherits from QObject base class Tells moc to parse the class contents QtCreator complains if missing 24

Special keywords signals keyword is used to start a block of signal definitions Signal functions are not implemented. Instead, the code for them is generated by moc Signals can have parameters as any normal function A slot that is connected to signal must have matching parameter count and types 25

Special keywords slots keyword starts a block of slot definitions Each slot is a normal C++ function Can be called directly from code Normal visibility rules apply when called directly from code However, signal-slot connections will ignore visibility and thus it s possible to connect to private slot from anywhere 26

Special keywords emit keyword is used to send a notification to all slots that have been connected to the signal Object framework code loops over the slots that have been connected to the signal and makes a regular function call to each 27

Connecting signals to slots Connections are made with QObject::connect static functions No access control, anyone can connect anything Class headers are not needed if signal and slot function signatures are known Component-based approach Components provide services Controller makes the connections between components 28

Signals and slots Comparing Qt and Java 29

Object properties CORE FEATURES 30

Object properties All QObject-based classes support properties A property is QVariant type, which is stored in a dictionary that uses C-style zero-terminated character arrays as keys i.e. name-value pair Properties can be dynamic or static Dynamic properties are assigned at run-time Static properties are defined at compile time and processed by the meta-object compiler 31

Object properties Static properties are declared into class header using Q_PROPERTY macro The above statement defines a property Type is qreal, name is rotation When read, rotation function is called When modified, setrotation function is called Changes are notified via rotationchanged signal 32

QML / C++ integration HYBRID PROGRAMMING 33

Exporting objects to QML Objects are registered with qmlregistertype template function Object class as template parameter Function parameters: Module name Object version number (major, minor) Name that is registered to QML runtime Details about modules from: http://doc.trolltech.com/4.7-snapshot/qdeclarativemodules.html 34

Using exported classes The exported classes can be used as any other QML component The module needs to be imported 35

Qt objects in QML Visibility at QML side QObject properties become element properties on<property>changed hook works if the NOTIFY signal is specified at C++ side - Also note that C++ signal name doesn t matter QObject signals can be hooked with on<signal> QObject slots can be called as functions 36

Graphics items Qt graphics items QGraphicsItem base class Not based on QObject for performance reasons Items are added to graphics scene A QML Item is based on QDeclarativeItem Inherits QGraphicsObject from Qt graphics framework http://doc.trolltech.com/4.7-snapshot/qdeclarativeitem.html Custom painting can be done on C++ side 37

Graphics items Multiple inheritance hierarchies QObject QGraphicsItem QGraphicsObject QAbstractGraphicsShapeItem QDeclarativeItem QGraphicsPolygonItem QML integration MyCustomQMLPolygon Painting Example in HelloQMLApp directory 38

Overview of QML animations BUILDING FLUID GUI 39

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 40

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 41

Animation types Property value sources Behavioral Standalone Signal handlers State transitions 42

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 43

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 44

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 45

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 46

Animation types Example code in AnimationExamples directory Uses NumberAnimation for various scenarios 47

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 48

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 49

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 50

GUI states and animated state transitions BUILDING FLUID GUI 51

GUI states A state represents a snapshot of a GUI Click on Edit Mouse on file name 52

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 53

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 54

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 55

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 56

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 57

State examples SequentialTransition directory Mapping the AnimationGrouping example into state framework StateExample directory 58

Models, views and delegates DISPLAYING DATA 59

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 60

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 61

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 62

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 63

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 64

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 Interpolated values forwarded to delegate (60,80) Example in PhotoExample directory 65

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 66

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 Cannot be used to store any state Thus, state must be stored in the model 67

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 68

View selection Each view has currentindex property ListView and GridView also 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 69

Adding states and transitions FLUID GUI EXERCISES 70

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

States and transitions Add an area to left side, which slides in when mouse is clicked on it Slides back when clicked again 72

Implementing a model and view DATA MODEL EXERCISE 73

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 74

75