100% found this document useful (1 vote)
765 views

QML Tutorial

QML is a declarative language for building user interfaces. It allows defining UI elements in a declarative way using XML-like syntax. Elements have properties that describe their appearance and behavior. Elements can be nested to build complex UIs. User interaction is handled through mouse areas, keyboard input, and focus scopes.

Uploaded by

Amanda Carr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
765 views

QML Tutorial

QML is a declarative language for building user interfaces. It allows defining UI elements in a declarative way using XML-like syntax. Elements have properties that describe their appearance and behavior. Elements can be nested to build complex UIs. User interaction is handled through mouse areas, keyboard input, and focus scopes.

Uploaded by

Amanda Carr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 16

qQT Quick

====================================
1. Introduction
====================================
a. QML Syntax
- A declarative markup language
- Language runtime integrated with QT
- Qt Created ICE support
- Graphical design tool
- C++ API for integration with Qt applications
- QML is based on javascript
b. Basic user interface composition skills
c. What is QML?
- Declarative
- Typeless
- Describes the user interface
- UI specified as a tree:
/QML
import Qt 5.1 // Bring in the Qt module, version 5.1
// Define a lightblue rectangle
Rectangle{ // This is an "element"
width:400; height:400 // these are properties
color: "lightblue"
/*
Multiline comment
*/
Text{}
Image{}
}
QML/
To run this: qmlviewer rectangle.qml
- Modules brought in with the import keyword
- Elements
a. Item is the root of all Elements
- Not visible
- Used as a container / top-level element
b. May be states, elements, models, paths, etc...
c. May extend with custom elements
d. Are described/defined by properties:
- Standard properties:
-----------------------------------
/QML
height: 40
text: "Hello"
QML/
- Grouped properties: (i.e. namespaces)
-----------------------------------
/QML
Text {
font.family: "Helvetica"
font.pixelSize: 24
}
QML/
- Identity property: gives the element a name
-----------------------------------
/QML
Text {
id: text
text: "Hello world"
}
QML/
If an id is not specified, the element is not available for modificati
on.
Kind of a poor mans' private scope
- Custom properties
-----------------------------------
/QML
Rectangle {
property real mass: 100.0 // Notice it is typed
}
Circle {
property real radius: 100.0 // Notice it is typed
}
QML/
- Binding properties
-----------------------------------
Property Binding = referring to the value of another property
/QML
import Qt 5.1
Item {
width:400; height:200
Rectangle{
x: 100; y: 50
width: height=*2; height:100 // Notice expression
color: "lightblue"
}
}
QML/
/QML
import Qt 5.1
Rectangle {
width:200; height:100
color: "lightblue"
TextInput {
x:20;y:20; // position is relative to the parent
width:160
font.pixelSize:32
text: "Qt Quick"
focus:true
onTextChanged:color="green" // Eventing and Property binding
}
}
QML/
e. id property
-----------------------------------
- Lets other elements to refer to it
- Used to create relationships between elements
- If there is none, your element is not available for modification.
Kind of a poor mans' private scope

/QML
import Qt 5.1
Item {
width: 300; height: 115 // necessary, as the default 0x0
Text {
id: text_element
x: 50; y: 50
text: "Qt Quick"
font.family: "Helvetica"; font.pixelSize: 50
}
Rectangle {
x: 50; y: 75; height: 5
width: text_element.width // referring to the previous item's width
color: "green"
}
}
QML/
- Methods
- All methods are public in QML
- There are some utility functions in the Qt. namespace
- Types
- Numbers (int and real)
- Boolean: true false
- Strings
- Constants: AlignLeft
- Lists: [...]
- Scripts
Bits of code that affect properties
- Others:
colors, dates, teims, rects, points, sizes, 3D vectors
usually created with constructors
2. Composing User Interfaces
=====================================================================
1. Nested Elements
-----------------------------------------
- Elements are most often nested
/QML
import Qt 5.1
Rectangle {
width: 400; height: 400
color: "lightblue"
Rectangle{
x:50; y:50; width:300; height:300
color:"green"
Rectangle {
x:200; y:150; width:50; height:50
color:"white"
}
}
}
QML/
- Each element is positioned relative to it's parent
- Nesting hides scope
2. Graphical Elements
-----------------------------------------
- Colors, gradients and images
- Create appealing UIs
- "red", "green"
- "#ffffff"
- Qt.rgba(0,0.5,0,1)
- opacity property runs from 0.0 to 1.0

- Images
- Represented with the Images element
- use the source property
- using absolute URLs
- or relative to the QML file
- transformations
- scale, rotation
- about an axis or central point
- transformOrigin: the point which the transformation is centered
transformOrigin: Item.Top
- Gradients
- Contains two or more GradientStop elements each with:
- a position between 0 to 1
- a color
- The start and stop points are on the top and bottom edges of the item an
d cannot be repositioned
- Issues:
- CPU intensive
- may not be animated as you expect
- Use image gradients instead
- Gradients override color definitions
3. Text Elements
-----------------------------------------
- Displaying text
- Use the Text element
- Height and width are determined from content
- You may use html in the value
- Handling text input
- Use the TextInput element

4. Anchor Layout
-----------------------------------------
- Allow elements to be placed in an intuitive way
- Maintain spatial relationships between elements
- Used to position and align itmes
- Line up the edges or central lines of items
- Anchors refer to:
- Other items (centerIn, fill)
- Anchors of other items (left, top)
/QML
import Qt 5.1
Rectangle {
width: 400; height: 400
color: "lightblue"
id: rectangle1
Text {
text: "Centered text"; color: "green"
font.family: "Helvetica"; font.pixelSize: 32
anchors.centerIn: rectangle1 // if Rectangle parent did not have an id,
we could specify "parent"
// anchors.right: parent.right <== ties it to the right side of the pare
nt element
}
}
QML/
- Margins
- Just like html:
topMargin, rightMargin, bottomMargin, leftMargin
- Are only used if the correspoinding anchors are used
i.e. leftMargin needs left to be defined
101
====================================
2. User Interaction
====================================
1. Implementing user interaction

- [Mouse Areas]
- Placed and resized like ordinary items
- use anchors if necessary
- Two ways to monitor mouse input:
- handle signals
- dynamic property bindings
- Hints and tips
- A mouse area only responds to its acceptedButtons
- the handlers are not called for other buttons, but
- any click involving an allowed button is reported
- the pressedButtons property contains all buttons
- even non-allowed buttons, if an allowed button is also pressed
- With hoverEnabled set to false
- containsMouse can be true if the mouse area is clicked
- [Keyboard Input]
- Two choices: TextInput and TextEdit
- Navigation between elements
- changing the focused element
- directional: arrow keys, tab, backtab
- Use KeyNavigation.tab: to assign next focused element
- Use KeyNavigation.right for right key
- Use KeyNavigation.left for left key

- [Raw keyboard Input]
- Can be handled by items
- With predefined handlers for commonly used keys
- full key event information is also available
- The same focus mechanism is used as for ordinary text input
- Key handling is not an inherited property of items
- But, is enabled by using the Keys attached property
- Key events can be forwarded to other objects
- Enabled by usin the Keys.forwardTo attached property
- Accepts a list of objects
Example:
-------------------
/QML
import Qt 5.1
Rectangle {
width: 400; height: 400; color: "black"
Image {
id: rocket
x: 150; y: 150
source: "../images/rocket.svg"
transformOrigin: Item.Center
}
Keys.onLeftPressed:
rocket.rotation = (rocket.rotation - 10) % 360
Keys.onRightPressed:
rocket.rotation = (rocket.rotation + 10) % 360
focus: true
}
// Or, you can inspect events
...
Keys.onPressed: {
if(event.key == Qt.Key_Left)
rocket.rotation = (rocket.rotation - 10) % 360
else if(event.key == Qt.Key_Right)
rocket.rotation = (rocket.rotation + 10) % 360
}
...
QML/
- [Focus]
- UIs with one TextInput, focus is automatically assigned
- If TextInput has no text you cannot click it unless it has a width or uses
anchors
- Set the focus property to assign focus
- [Focus Scopes]
- Focus scopes are used to manage focus for items
- FocusScope delegates focus to one of its children
- When the focus scope loses focus
- remembers which one has the focus
- When the focus scope gains focus again
- restores focus to the previously active item
Example:
---------------------
/QML
import Qt 5.1
Rectangle {
width: 400; height: 200

// Nice gradient background image
Image {
source: "../images/background.png"
}
// Top Button
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: parent.top
anchors.topMargin: 15
width: 350; height: 75
color: mouse_area.containsMouse ? "green" : Qt.rgba(1.0,0.25,0.25,0.5)
radius: 10 // curved corners
// Button image
Image {
id: image1
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
source: "../images/rocket.svg"
scale: 0.4
// Create a clickable area
MouseArea {
id: mouse_area
anchors.fill: parent // All of the parent is clickable
onPressed: parent.color = "green" // signal handler
onReleased: parent.color = "black" // signal handler
hoverEnabled: true // will receive hover events
}
}
// Adjacent button image text
Text {
text: "Launch"
anchors.left: image1.right
anchors.leftMargin: 20
anchors.verticalCenter: parent.verticalCenter
}
}
// Bottom Button
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
anchors.bottomMargin: 15
width: 350; height: 75
color: Qt.rgba(1.0,0.25,0.25,0.5)
radius: 10 // curved corners
// Button image
Image {
id: image2
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
source: "../images/clear.svg"
scale: 0.4
// Create a clickable area
MouseArea {
id: mouse_area
anchors.fill: parent // All of the parent is clickable
onPressed: parent.color = "green" // signal handler
onReleased: parent.color = "black" // signal handler
hoverEnabled: true // will receive hover events
}
}
// Adjacent button image text
Text {
text: "Clear"
anchors.left: image2.right
anchors.leftMargin: 20
anchors.verticalCenter: parent.verticalCenter
}
}
// text input
TextInput {
id: name_field
anchors.left:parent.left; y:16
anchors.right:parent.right
text: "Field 1"; font.pixelSize: 32
color: focus ? "black":"gray"
focus: true
KeyNavigation.tab: address_field
}
TextInput {
id: address_field
anchors.left:parent.left; y:16
anchors.right:parent.right
text: "Field 1"; font.pixelSize: 32
color: focus ? "black":"gray"
KeyNavigation.tab: name_field
}
}
QML/
2. State Handling
- [States]
- States manage named items
- Represented by the State element
- Each item can define a set of states
- With the states property
- Current state is set with the state property
- Properties are set when a state is entered
- Can also
- Modify anchors
- change the parents of items
- run scripts
Example:
-------------------------
/QML
import Qt 5.1
Rectangle {
width: 150; height: 250

Rectangle {
id: stop_light
x: 25; y: 15; width: 100; height: 100
}
Rectangle {
id: go_light
x: 25; y: 135; width: 100; height: 100
}
states: [
State {
name: "stop"
// Element that specifies property changes for a named element
PropertyChanges {target: stop_light; color: "red"}
PropertyChanges {target: go_light; color: "black"}
},
State {
name: "go"
PropertyChanges {target: stop_light; color: "black"}
PropertyChanges {target: go_light; color: "red"}
}
]
// define an initial state
state: stop
// Toggle states
MouseArea {
anchors.fill: parent
onClicked: parent.state == "stop" ? parent.state = "go" : parent.state = "
stop"
}
}
QML/
- [State Conditions]
- Let the State decide when to be active
- using conditinos to determine if a state is active
- Define the when property
- using an expression that evaluates to true or false
- only one state in a states list should be active
- Ensure when is true for only one state

Example:
------------------------
/QML
import Qt 5.1

Rectangle {
width: 150; height: 250

TextInput {
id: text_field
text: "Enter text..."
}
Image {
id: clear_button
source: "../images/clear.svg"
MouseArea {
anchors.fill: parent
onClicked: text_field.text = ""
}
}
// Default state and current state is implicit
states: [
State {
name: "with text"
when: text_field.text != ""
PropertyChanges {target:clear_button; opacity: 1.0}
},
State {
name: "without text"
when: text_field.text == ""
PropertyChanges {target:clear_button; opacity: 0.0}
PropertyChanges {target:text_area; focus:true}
}
]
}
QML/
2. Transitions
- Define how items change when switching states
- Applied to two or more states
- Usually describe how items are animated
Example:
------------------------
/QML
import Qt 5.1

Rectangle {
width: 150; height: 250

TextInput {
id: text_field
text: "Enter text..."
}
Image {
id: clear_button
source: "../images/clear.svg"
MouseArea {
anchors.fill: parent
onClicked: text_field.text = ""
}
}
// Default state and current state is implicit
states: [
State {
name: "with text"
when: text_field.text != ""
PropertyChanges {target:clear_button; opacity: 1.0}
},
State {
name: "without text"
when: text_field.text == ""
PropertyChanges {target:clear_button; opacity: 0.0}
PropertyChanges {target:text_area; focus:true}
}
]
// Work in conjunction with states
transitions: [
Transition {
from: "stop"; to: "go" // states
PropertyAnimation {
target: stop_light
properties: "color"; duration: 1000
}
},
Transition {
from: "go"; to: "stop" // states
PropertyAnimation {
target: stop_light
properties: "color"; duration: 1000
}
}
// Or you could:
Transition {
from: "*"; to: "*" // any states
PropertyAnimation {
target: stop_light
properties: "color"; duration: 1000
}
}
//...And reversible:
Transition {
from: "stop"; to: "go" // states
reversible: true // No need to define two transitions!
PropertyAnimation {
target: stop_light
properties: "color"; duration: 1000
}
},
]
}
QML/
3. Animations
=====================================================================

- Can apply animations to user interfaces
- Can queue animatinos
- Can be applied to any visible element
- All animations are property animations
- Easing curves created variable speed animations
- Specialized Animations:
- NumberAnimation: for changes to numeric properties
- ColorAnimation: for changes to color properties
- RotationAnimation: for changes to oreintation of items
- Vertor3dAnimation: for motion in 3D space
- Example:
--------------------------------
/QML
import Qt 4.7
Rectangle {
width: 400; height: 400
color: "lightblue"
Rectangle {
id: rectangle1
y: 150; width: 100; height: 100
color: "green"
NumberAnimation on x { // x is the property being acted upon
from: 0; to: 150
duration: 1000
}
}
// Or you may do it out-of-line
// You may do the same with NumberAnimation {...}
PropertyAnimation {
target: rectangle1
properties: "width,height"
from: 0; to: 100; duration: 1000
running: true // Whether the animation is enabled or disabled
}
}
QML/
- [Easing Curves]
- Specify with the easing.type property:
easing.type: "..."
- [SequentialAnimation]
- defines a sequence
/QML
SequentialAnimation {
NumberAnimation {
target: item1; properties: "scale"
from: 1.0 to: 0.5; duration: 1000
}
NumberAnimation {
target: item1; properties: "opacity"
from: 1.0 to: 0.0; duration: 1000
}
running: true
}
QML/
- [ParallelAnimation]
- defines a parallel group
- Animations will be synchronzied
/QML
ParallelAnimation {
NumberAnimation {
target: item1; properties: "scale"
from: 1.0 to: 0.5; duration: 1000
}
NumberAnimation {
target: item1; properties: "opacity"
from: 1.0 to: 0.0; duration: 1000
}
running: true
}
QML/
- [PauseAnimation]
/QML
SequentialAnimation {
NumberAnimation{...}
PauseAnimation{ duration: 1000}
NumberAnimation{...}
running:true
}
QML/
- [ColorAnimation]
/QML
ColorAnimation {
target: item1
property: "color"
from: Qt.rgba(0,0.5,0,1)
to: Qt.rgba(1,1,1,1)
duration: 1000
running: true
}
QML/
- [RotationAnimation]
- Easier to use than NumberAnimation
- Applied to the rotation of an item
- Value of the direction property controls rotation:
- RotationAnimation.Clockwise
- RotationAnimation.Counterclockwise
- RotationAnimation.Shortest - the direction of least angle between from a
nd to
/QML
Image {
id: item1
source: "../images/ball.png"
anchors.centerIn: parent
smooth: true
RotationAnimation on rotation {
from: 45; to: 315
direction: RotationAnimation.Shortest
duration:1000
}
}
QML/
3. Presenting Data
=====================================================================
- Arranging Items
= Positioners
- Arrange items in standard layouts
- Column
- Row
- Grid
- Flow
- Anchors can be used inside of Column, Row, and Grid
= Repeaters
- for use with positioners
- using data from a model
- Examples:
-----------------------------------
/QML
import Qt 5.1

// Lays out the Rectangles left to right in a nice cube
Grid { // Positioner
x:15; y:15 // position of first item
width:300; height: 300
columns:2; rows:2; spacing:20
Rectangle{width: 125; height: 125; color:"red"}
Rectangle{width: 125; height: 125; color:"green"}
Rectangle{width: 125; height: 125; color:"sliver"}
Rectangle{width: 125; height: 125; color:"blue"}
}
// Now, the repeater
Rectangle { // Simply a space to contain our stuff
width:300; height: 300; color: "black"

Grid { // Positioner
x: 5; y: 5
rows: 5; columns: 5; spacing: 10
Repeater {
model: 24 // count of items
Rectangle{
width: 70; height: 70; color: "lightgreen"
Text {
text: index // The count of the current item
font.pointSize: 30
anchors.centerIn: parent
}
}
}
}
}

QML/
- the model property can take an object or functyion:
/QML
model: {
var board=[true]
for(var i=1; i<64; i++)
board[i] = false;
board;
}
QML/
= Consequently, other properties can take logic to - like color: {if x "bl
ack" else "green"}
= However, changing properties in bindings is expensive, as it's run on ea
ch iteration.
It's better to change your data model
- Data Models
- Pure
- ListModel
/QML
ListModel {
id: name_model
ListElement {name: "Alice"}
ListElement {name: "Bob"}
ListElement {name: "Jane"}
}
QML/
- ListModel is a dynamic list of items
- append
name_model.append({"name": "Victor"})
- remove
name_model.remove(2)
- move
name_model.move(1,2, number) // investigate - unclear example
- Defining Delegates
- Define a Component to use as the delegate (There is no delegate keyw
ord)
- Give it an id
- describes how the data will be displayed
- Properties of list elements can be referenced
- In the item inside a Component
- The parent property refers to the view
- A ListView attached property can also be used to access the view
/QML
Component {
id: name_delegate
Text {
text: name // the name property of the ListElements above
font.pixelSize: 32
}
}
QML/

- Using a List Model
/QML
Column {
anchors.fill: parent
Repeater {
model: name_model // see above
delegate: name_delegate // see above
}
}
QML/
- XmlListModel

- XML
- Visual
- VisualItemModel
- Contains child items that are supplied to views
/QML
VisualItemModel {
id: labels
Rectangle {...all sorts of stuff...}
Rectangle {...more stuff...}
}
// Then, feed the model to a repeater
Column { // arranges the items
Repeater {model: labels} // emits the items
}
QML/
- VisualDataModel
- Contins an interface to an underlying model
- Supplies a delegate for rendering
- Views (works with pure models)
- ListView
- Shows a classic list
- Is flickable
/QML
ListView {
id: listView
anchors.fill: parent
model: name_model // from above
delegate: name_delegate // from above
clip: true // overflow hidden
header: Rectangle {
width: parent.width; height: 10; color: "pink"
}
footer: Rectangle {
width: parent.width; height: 10; color: "lightblue"
}
highlight: Rectangle { // highlights the current item
width: parent.width; height: 10; color: "lightgray"
}
interactive:false // disables flicking
}
// To get the current item:
listView.currentItem.text
QML/
- GridView
Shows a classic grid

You might also like