diff options
Diffstat (limited to 'doc/src/qtquick2/qmlintro.qdoc')
-rw-r--r-- | doc/src/qtquick2/qmlintro.qdoc | 1234 |
1 files changed, 1234 insertions, 0 deletions
diff --git a/doc/src/qtquick2/qmlintro.qdoc b/doc/src/qtquick2/qmlintro.qdoc new file mode 100644 index 0000000000..b8b714effe --- /dev/null +++ b/doc/src/qtquick2/qmlintro.qdoc @@ -0,0 +1,1234 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** GNU Free Documentation License +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms +** and conditions contained in a signed written agreement between you +** and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! +\page qml-intro.html tutorial +\title Introduction to the QML Language +\brief Introduction to the concepts and features behind QML. + +QML is a declarative language designed to describe the user interface of a +program: both what it looks like, and how it behaves. In QML, a user +interface is specified as a tree of objects with properties. + +This introduction is meant for those with little or no programming +experience. JavaScript is used as a scripting language in QML, so you may want +to learn a bit more about it (see the online \l{Javascript Guide}) before +diving deeper into QML. It is also helpful to have a basic understanding of +other Web technologies like HTML and JSON, but it is not required. + +The examples shown in this guide are located in the +\c{examples/declarative/tutorials/qmlintro} directory within the Qt source +package. You can run then with the \l{QML Viewer} tool. + +\section1 \l{QML Concepts and Syntax} +\tableofcontents{1 QML Concepts and Syntax}{section4} + +\section1 \l{Composing User Interfaces with QML} +\tableofcontents{1 Composing User Interfaces with QML}{section4} + +\section1 \l{User Interaction with QML} +\tableofcontents{1 User Interaction with QML}{section4} +*/ + +/*! +\page qml-basic-syntax.html +\brief The basic syntax and concepts of the QML language. +\contentspage Introduction to the QML Language +\previouspage Introduction to the QML Language +\nextpage Composing User Interfaces with QML +\title QML Concepts and Syntax + +\tableofcontents + +This chapter covers the basic syntax of the QML language through the +use of examples, introducing the concepts behind the language and +the terminology used in the reference documentation. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-basic-syntax.png +\enddiv +The following example shows the basic syntax of QML. When opened in +the \l{QML Viewer}{\QQV tool}, the output displayed should match the +image shown on the right: a light blue rectangle. + +\snippet examples/declarative/tutorials/qmlintro/basic-syntax.qml document + +In this example, we import the features defined by Qt Quick 1.0, and +we declare and create a single rectangle with width, height and color. +Let's take a look at the main points of the language introduced by +this simple example. + +\section1 Importing Modules + +The \c import statement imports the \c QtQuick \l{QML Modules}{module}, +which contains all of the standard \l{QML Elements}. Without this import +statement, the \l Rectangle and other elements would not be available. + +A specific version of a module is imported. This guarantees that the +elements imported when the application is run by the user match those +used by the developer when the application was written, ensuring that +they have the expected behavior. + +\section1 Elements + +The rectangle in the above example is specified by the \l Rectangle +element. When we declare objects like this, we write the element's type +followed by a pair of braces in between which additional data can be +defined for the object, such as its property values and any child objects. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-elements1.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/elements1.qml document + +Here, we create two elements: a rectangle with an image inside it. We say that +the rectangle is the parent element and the image is its child. Since the +rectangle does not have a parent element, it is a top level element. + +The position of each element in the user interface is defined relative +to the position of its parent, except for the top level element whose +position is always the top-left corner of the screen. + +QML files can contain multiple elements, but \e{only one} can be a top level +element. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-elements2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/elements2.qml document + +In this example, we can define as many elements inside the rectangle +as we like, but we cannot define other top level elements. All the +additional elements are defined inside the light blue rectangle. + +\note In the QML documentation, we refer to \e elements, \e items and +\e components, often interchangeably. + +\list +\li When we talk about an \e element, we usually mean the syntactic structure, + including the name, the opening and closing braces, and its contents. +\li An \e item is an element that has a visual appearance. All items are + elements that inherit \l Item either directly or indirectly. For example, + a \l Rectangle is an item, but a \l State is an element because it does + not have an intrinsic appearance. +\li A \e component is an element that is defined to be reused. In many cases, + components are often items, too. +\endlist + +For now, we will refer to elements and items. Components are discussed in +detail later in this guide. + +A list of the most common elements is described on the \l{QML Basic Elements} +page. A full list can be found on the \l{QML Elements} page. + +\clearfloat +\section1 Properties + +A QML element usually has various \e properties that help define the element. +For example, all items have the \l{Item::}{x} and \l{Item::}{y} properties +that define the position of the item relative to its parent item (or the +screen's origin) and \l{Item::}{width} and \l{Item::}{height} properties +that define its dimensions. All simple properties have names that begin +with a lower case letter. + +\section2 Setting Properties + +Properties are specified with a \c{property: value} syntax. In the above +example, we can see the \l Image object has a property named \c source, +which has been assigned the value \c{"pics/logo.png"}. The property and its +value are separated by a colon. + +Properties can be specified one-per-line: + +\qml +Rectangle { + width: 100 + height: 100 +} +\endqml + +or you can put multiple properties on a single line: + +\qml +Rectangle { width: 100; height: 100 } +\endqml + +When multiple property-value pairs are specified on a single line, they +must be separated by a semicolon. + +\section2 Basic Property Types + +QML supports properties of many types (see \l{QML Basic Types}). The basic types +include \c int, \c real, \c bool, \c string and \c color. + +\qml +Item { + x: 10.5 // a 'real' property + state: "details" // a 'string' property + focus: true // a 'bool' property + // ... +} +\endqml + +QML properties are what is known as \e type-safe. That is, they only allow you +to assign a value that matches the property type. For example, the \c x property +of item is a real, and if you try to assign a string to it you will get an error. + +\badcode +Item { + x: "hello" // illegal! +} +\endcode + +Property values are dynamic, responding to changes in the user interface. +See the \l{#Property Change Notifications}{Property Change Notifications} +section for information on the different ways to define properties, bind +them together and react to changes. + +\section2 Grouped Properties +\target dot properties + +Some elements contain a set of related properties that form a logical group; +these use a "dot" or grouped notation to show this. The \l Text item is one +such item that uses groups of properties to describe the font used to +display text. + +Grouped properties can be written like this: + +\snippet examples/declarative/tutorials/qmlintro/grouped-properties1.qml text with grouped properties + +or like this: + +\snippet examples/declarative/tutorials/qmlintro/grouped-properties2.qml text with grouped properties + +In the element documentation, grouped properties are shown using the "dot" notation. + +\section2 List Properties + +Some properties contain lists of elements, such as \l State, \l Item or +\l Transition. For example, the \l{Item::}{states} property is used like +this: + +\qml +Item { + states: [ + State { name: "stop" }, + State { name: "go" } + ] +} +\endqml + +The list is enclosed in square brackets, with a comma separating the list +elements. In cases where you are only assigning a single element to a list, +you can omit the square brackets: + +\qml +Item { + states: State { name: "stop" } +} +\endqml + +Elements in the list can be accessed by index. See the \l{list}{list type} +documentation for more details about list properties and their available +operations. + +\section1 Expressions + +JavaScript expressions can be used to assign property values. For example: + +\qml +Item { + width: 100 * 3 + height: 50 + 22 +} +\endqml + +These expressions can include references to other objects and properties, in +which case a \l{Property Binding in QML}{binding} is established: when the value of +the expression changes, the property to which the expression is assigned is +automatically updated to the new value. For example: + +\div {class="float-right"} +\inlineimage declarative-qmlintro-property-binding1.png +\br +\inlineimage declarative-qmlintro-property-binding2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/property-binding.qml elements + +Here, the child \l Rectangle item's \c width property is set relative to +the width of its parent. Whenever the parent's width changes, the width of +the \l Rectangle is automatically updated. This uses the special \c parent +property to refer to a parent item, which we explore in the +\l{Object Identifiers}{next section}. + +This is useful for relating the size of one element to another, so that +changes to the sizes of elements in the design, or at run-time, will be +taken into account. + +Property binding works with all types of properties, not just those related +to the size of an element. + +\section1 Object Identifiers + +Each object can be given a special \e id value that allows the object to +be identified and referred to by other objects. An \c id must begin with +a lower-case letter or an underscore, and cannot contain characters other +than letters, numbers and underscores. + +For example, below we define a \l Text element and a \l Rectangle element +as children of a \l Column element. The \l Text object has an \c id value +of \c{textElement}. The Rectangle object defines its \c width property +to be the same as that of the Text object by referring to +\c{textElement.width}: + +\div {class="float-right"} +\inlineimage declarative-qmlintro-object-identifiers.png +\enddiv + +\snippet examples/declarative/tutorials/qmlintro/object-identifiers.qml document + +An object can be referred to by its \c id from anywhere within the +\l{QML Documents}{component} in which it is declared. Therefore, an +\c id value must always be unique within a single component. +This means that a single QML file should only contain one place where +a particular \c id value is defined. + +The \c id value is a special value for a QML object and should not be +thought of as an ordinary object property; for example, it is not possible +to access \c{textElement.id} in the above example. Once an object is +created, its \c id cannot be changed. + +\note The \c parent value is a special identity that each element can use +to refer to its parent item. For most simple user interfaces containing +a few display items, the parent of an item will be the enclosing element +in the QML file that contains it. However, when we look at more complex +ways to arrange and display items, we will find that this is not always +the case. + +\section1 Comments + +Commenting in QML is similar to JavaScript. +\list +\li Single line comments start with // and finish at the end of the line. +\li Multi-line comments start with /* and finish with *\/ +\endlist + +Comments are ignored by the QML engine. They are useful for explaining what +you are doing; for referring back to at a later date, or for others reading +your QML files. + +\snippet examples/declarative/tutorials/qmlintro/comments.qml commenting + +Comments can also be used to prevent the execution of code, which is +sometimes useful for tracking down problems. In the above example, the +\l Text element will have normal opacity, since the line containing the +opacity property has been turned into a comment. + +\section1 Responding to Changes + +User interfaces created using QML contain items such as \l Rectangle, +\l Image and \l Text to display content, but they can also contain items +that accept user input, such as \l TextInput and \l MouseArea. When the +user interacts with these items, they emit signals to inform other +components of any change. These signals can be received by the items +themselves; this is the main way to create items that respond to the user. + +\section2 Signal Handlers + +Signal handlers allow JavaScript code to be executed in response to a signal. +For example, the \l MouseArea element has an \l{MouseArea::}{onClicked} handler +that can be used to respond to a mouse click. Below, we use this handler to +print a message whenever the mouse is clicked: + +\snippet examples/declarative/tutorials/qmlintro/signal-handlers.qml document + +All signal handlers begin with \e "on". + +Some signal handlers include an optional parameter. For example +the MouseArea \l{MouseArea::}{onPressed} signal handler has a \c mouse parameter +that contains information about the mouse press. This parameter can be +referred to in the JavaScript code, as below: + +\snippet examples/declarative/tutorials/qmlintro/signal-handlers-parameters.qml mouse area + +\section2 Property Change Notifications + +When a property changes value, it can send a signal to notify others of this change. + +To receive these signals, simply create a \e{signal handler} named with an +\e on<Property>Changed syntax. For example, the \l TextInput element has a +\l{TextInput::}{text} property. When this property changes, the \c textChanged +signal is emitted. We can monitor this property for changes with the +\c onTextChanged handler. + +\table +\header \li Property \li Signal \li Signal Handler +\row \li \l{TextInput::}{text} \li \c textChanged \li \c onTextChanged +\endtable + +The following code shows this in practice: + +\div {class="float-right"} +\inlineimage declarative-qmlintro-property-change1.png +\br +\inlineimage declarative-qmlintro-property-change2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/property-change.qml property change + +When the user modifies the text, the expression assigned to the \c textChanged +handler will be evaluated. In this example, the text changes color when this +happens. + +Similarly, the \l Rectangle element has \l{Item::}{width} and +\l{Rectangle::}{color} properties. Below, we have a \l Rectangle element +that has defined two signal handlers, \c onWidthChanged and \c onColorChanged, +which will automatically be called whenever these properties are modified: + +\qml +Rectangle { + width: 100; height: 100 + + onWidthChanged: console.log("Width has changed to:", width) + onColorChanged: console.log("Color has changed to:", color) +} +\endqml + +These cause the new values of these properties to be written to the console, +which can be useful for debugging purposes. + +\section2 Attached Properties +\target attached-properties + +Some elements attach properties to other elements. This is used in cases +where one element needs to access features of another, but does not +inherit properties to access those features. + +Attached Properties are of the form \e {<Type>.<property>} where \e <Type> +is the type of the element that attaches \e <property>. + +An example of attached properties in use involves the \l Keys element which +attaches properties for handling key presses to any item. For example: + +\div {class="float-right"} +\inlineimage declarative-qmlintro-attached-properties.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/attached-properties.qml attached properties + +The \l Keys properties are not defined by the \l Item element. They are +defined separately and attached to the item. + +Attached properties are also used by delegates to reference information about +the view they are used in. For example, the \l ListView element attaches +the \e ListView.isCurrentItem property to each delegate it creates: + +\div {class="float-right"} +\inlineimage declarative-qmlintro-attached-properties-view.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/attached-properties-view.qml delegate with attached property + +In effect, by attaching this property, \l ListView provides an interface +that lets the delegate access information about the current item in the +view it appears in. + +The use of attached properties will be covered in more depth later in this +guide. + +\omit +\section2 Default Properties + +Each object type can specify one of its list or object properties as its default property. +If a property has been declared as the default property, the property tag can be omitted. + +For example this code: +\qml +State { + changes: [ + PropertyChanges {}, + PropertyChanges {} + ] +} +\endqml + +can be simplified to: + +\qml +State { + PropertyChanges {} + PropertyChanges {} +} +\endqml + +because \c changes is the default property of the \c State type. +\endomit +*/ + +/*! +\page qml-composing-uis.html +\contentspage Introduction to the QML Language +\previouspage QML Concepts and Syntax +\nextpage User Interaction with QML +\title Composing User Interfaces with QML +\brief How to arrange items with anchors. + +\tableofcontents + +In the \l{Introduction to the QML Language}{previous chapter}, we looked at +the syntax of QML and the basic building blocks that are used to create +user interfaces. For example, at a low level, we have seen that an item's +\c x and \c y properties are used to position it within its parent item. +However, when defining more complex user interfaces, especially those with +items that will move or change size, we need a way to arrange items in a +more systematic way. + +\section1 Anchors and Anchor Lines + +In the previous examples, all the items have been given either absolute +positions in the user interface or positions relative to their parents. +For more flexibility, both at design-time and in the case where the user +interface changes at run-time, we prefer to use anchors to arrange items. + +Anchors connect items together visually, creating relationships between +their geometries. As a result, mixing absolute positioning and anchors +is only recommended in cases where the constraints imposed by each +approach do not conflict. Anchors can only be used to relate items +with their parents, children or siblings. + +\section2 Anchoring within Items + +Anchors can be used to generally describe how items are positioned +within the space occupied by their parents. Two of the anchors are used +to place items in this way. + +The following example uses anchors to position a \l Text item in the +center of a \l Rectangle. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-anchors-centerin.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/anchors.qml centered text + +In this case, the center of the text item is anchored to the center of +its parent item by using the \c{anchors.centerIn} grouped property. +This defines a high level description of the relationship between the two +items. Similarly, the \c{anchors.fill} grouped property is used to describe +the case where an item needs to fill the space provided by its parent. + +\note When using \c{anchors.centerIn} and \c{anchors.fill}, the value of +the anchor property is an item. + +\section2 Anchor Lines + +At a lower level, anchors can be used to line up the edges of two items. +In the following example, the \l Text item is centered within its parent, +the \l Item that defines the user interface. The \l Rectangle uses anchors +to define its position relative to the text item. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-anchors-edges.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/anchors2.qml anchored items + +By giving the text item the \c textItem identifier, we can refer to it when +defining the anchors for the rectangle. We line up the right edge of the +rectangle with the left edge of the text item, and line up their top edges. + +This example shows the use of anchor lines. Grouped properties are defined +for key parts of each item, including its top, left, right and bottom edges, +plus the lines running through the horizontal center and vertical center of +the item. A baseline anchor line is also used for items that display text. + +\note We connect anchor lines to other anchor lines, not to items. + +\section2 Anchors and Property Bindings + +Since the anchor definitions are property bindings, any changes to the +position of an anchor will cause any connected anchors to move as well. +This is illustrated by the following example, which places a red rectangle +beneath a \l TextInput item and uses anchors to ensure that it is always +the same width. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-anchors-expanding1.png +\br +\inlineimage declarative-qmlintro-anchors-expanding2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/anchors-expanding.qml anchored items + +The anchor lines on the left and right edges of the rectangle are connected +to those of the text input item. Since the text can be modified by the user, +the width of the item can change. The use of anchors causes the width of the +rectangle to change as well. + +The \l{Anchor-Based Layout in QML} document covers the use of anchors in +more detail. + +\clearfloat +\section2 Margins + +Although anchors are useful for lining up items, it is often useful to leave +small gaps between the edges of adjacent items. The following example lines +up an \l Image item with a \l Text item, but uses a margin to leave a gap +between them. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-anchors-margins.png +\br +\inlineimage declarative-qmlintro-anchors-baseline-margins.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/anchors-margins.qml anchored items + +Note that the image also uses a margin to leave a gap between its left edge +and the left edge of the user interface. + +Adding \l Rectangle items to the scene description, we can see the effects of +the anchors and margins, with the image displaced from the left edge of its +parent item and the text label displaced from the right edge of the image. + +\clearfloat +\section2 Limitations and Strategies + +Anchors allow the relationships between items to be described using simple +declarations, maintaining a user interface layout when items move or change +size. They are useful in most situations, but have limitations which need +to be considered, and therefore it is a good idea to adopt strategies for +using them. + +\section3 Limitations of Anchors + +Since anchors can only be used to relate an item with its parent, children or +siblings, care must be taken when referencing items in complex or deeply-nested +user interfaces. Where there are lots of items to be arranged, it can be more +productive to use \l{#Positioners}{positioners} and +\l{Generating Items with Repeaters}{repeaters}, or +\l{QML Models and Views}{models and views}. + +Connections between anchors cannot be deleted and will override explicit +declarations of positions and sizes using the \l{Item::}{x}, \l{Item::}{y}, +\l{Item::}{width} and \l{Item::}{height} properties of items. + +Since anchors rely on property binding to ensure that items are dynamically +updated if one of them changes, each anchor definition creates a new dependency +on another item. Use of anchors therefore causes a dependency graph defining an +order in which items will be updated. Problems can occur if circular dependencies +are created between items. The following example shows this occurring with a +parent item and its child. + +\snippet examples/declarative/tutorials/qmlintro/circular.qml circular + +\section3 Strategies for Use + +In order to reference an item with an anchor, it needs a way to be identified. +Children of the item can refer to it as \c parent, but otherwise it needs to +define an \l{Introduction to the QML Language#Object Identifiers}{identifier}. +It is good practice to define identifiers for all the items that need to be +positioned or referenced in some way unless those items can be referenced +using the \c parent identifier. + +It is usually helpful to identify the fixed or dominant parts of the user +interface and give those items identifiers so that dependent items can refer +to them. This avoids potential issues with circular dependencies. +In the example shown, the \c launchBox and \c cancelBox items are anchored +within the top level item that contains the user interface. Each of these +items contain an image and a text item that are anchored to their parent. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-anchors-strategy-annotated.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/anchors-strategy.qml anchor strategy + +The above example shows how each item is anchored to its parent. This ensures +that the dependencies introduced by the anchors all consistently point to each +item's parent or a sibling. It is not always possible to ensure such simple +dependencies between items. As a result, it is often necessary to consider +other factors that determine how the use of anchors will affect the geometries +of items. + +When positioning items using the \c horizontalCenter anchor, do not use the +\c left or \c right anchors; define the width of the item instead, either as +a fixed value or as a proportion of the parent item. Similarly, avoid using +the \c top or \c bottom anchors with the \c verticalCenter anchor; set the +height of the item instead. + +Items that define their own width and height based on their contents, like +\l Image or \l TextInput, can be used with all kinds of anchors. Care must +be taken to avoid imposing conflicting constraints on their dimensions. +For example, using \c left and \c right anchors to position a text input +item may be problematic because the item determines its own width and it +may change. + +When defining an item that you want to stretch to fill the available space +between other items, make sure that you anchor the stretchable item to items +with well-defined or implicitly-defined sizes and not the other way round. +The following example shows this with a \l Text item with an implicit size +and a \l Rectangle that stretches to fill the remaining space in its parent +item. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-anchors-stretch.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/anchors-stretch.qml items + +The rectangle uses anchors to define its top, left and right edges in terms +of its parent item, and the bottom edge is aligned with the top of the text +item. If, instead, the text item is anchored to the rectangle, which has no +implicit size, the layout of the user interface will be broken because the +rectangle will be assigned a zero height. + +\section1 Positioners + +Positioner items are container items that manage the positions and sizes of +items in a declarative user interface. Positioners behave in a similar way to +the \l{Widgets and Layouts}{layout managers} used with standard Qt widgets, +except that they are also containers in their own right. + +Positioners make it easier to work with many items when they need to be +arranged in a regular layout. As we will see when we encounter +\l{Generating Items with Repeaters}{Repeaters}, it is easier to describe +how items should be arranged when there are many of them than it is to +try and individually position them. + +\section2 Standard Positioners + +A set of standard positioners are provided in the basic set of Qt Quick items. +Since these are all based on the \l Item element, they contain properties that +define their positions and sizes, but they do not have any visual appearance +of their own; they simply arrange their child items in the space allocated to +them. Any background color, if desired, must be added to a parent Rectangle. + +\list +\li \l{#Row}{Row} arranges its children in a row. +\li \l{#Column}{Column} arranges its children in a column. +\li \l{#Grid}{Grid} arranges its children in a grid. +\li \l{#Flow}{Flow} arranges its children like words on a page. +\endlist + +Each of these items provides many of the same properties as the others, +making it easy to exchange one with another at a later point in the design +of an application or component. The common properties are \c spacing, +\c add and \c move. As expected, the \l{Row::spacing}, \l{Column::spacing} +and \l{Grid::spacing} properties have slightly different meanings because +they describe how space is added to different kinds of layout. + +The \c add and \c move properties describe what should happen when items +are added to a positioner item or moved within it. These actions are +described with \l{QML Animation and Transitions}{transitions}, and will +be covered later. + +\section3 Row + +\l Row items are used to horizontally arrange items. The following example +uses a Row item to arrange three rounded \l Rectangle items in an area defined +by an outer colored Rectangle. The \l{Row::spacing}{spacing} property is set to +include a small amount of space between the rectangles. + +\div {class="float-right"} +\inlineimage qml-row.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/row.qml document + +We ensure that the parent \l Rectangle is large enough so that there is some space +left around the edges of the horizontally centered Row item. The equally-sized +rectangles in this example automatically line up because they each have the +same height. Items with different heights will not be positioned vertically +by the \l Row; these need to be lined up using anchors. + +Since the \l Row item is responsible for positioning its child items +horizontally, those child items cannot use anchors to position themselves +within the row. However, they can use anchors to align themselves vertically +relative to one another or to the row itself. The following example uses +\c verticalCenter anchors to vertically align three rectangles with +different sizes. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-row-anchors.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/row-anchors.qml row + +Note that the \l Row item itself uses \c horizontalCenter and \c verticalCenter +anchors to place itself in the center of its parent. It is free to do this +because it is not being positioned by its parent, a \l Rectangle. However, +when we place positioners inside other positioner, such as a \l Row inside +a \l Column, we will need to be aware of what constraints are being imposed +by the positioner's parent item. This is +\l{#Nesting Positioner Items}{discussed later} in this chapter. + +The height of the row is dependent on the heights of the individual child +items and, unless specified using the \c height property or with anchors, +it will only be as high as the tallest child item. + +\clearfloat +\section3 Column + +\l Column items are used to vertically arrange items. The following example +uses a Column item to arrange three \l Rectangle items in an area defined +by an outer \l Item. The \l{Column::spacing}{spacing} property is set to +include a small amount of space between the rectangles. + +\div {class="float-right"} +\inlineimage qml-column.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/column.qml document + +In the above example, each of the rounded rectangles are positioned by the +\l Column item. The column only changes the vertical positions of its +child items and does not restrict their horizontal positions. However, +the restrictions on the use of anchors do not apply to the children of +these child items, so each \l Text item uses its \c centerIn anchor to +horizontally and vertically align itself within its parent rectangle. + +The width of the column is dependent on the widths of the individual child +items and, unless specified using the \c width property or with anchors, +it will only be as wide as the widest child item. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-column-anchors.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/column-anchors.qml document + +The example above stretches the column horizontally to fill the entire +user interface, and stretches each rectangle inside to fill the column. +The text items behave as they did in the previous example. + +\clearfloat +\section3 Grid + +\l Grid items are used to place items in a grid or table arrangement. +The following example uses a Grid item to place four \l Rectangle items +in a 2-by-2 grid. As with the other positioners, the spacing between items +can be specified using the \l{Grid::spacing}{spacing} property. + +\div {class="float-right"} +\inlineimage qml-grid-spacing.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/grid-spacing.qml document + +There is no difference between horizontal and vertical spacing inserted +between items, so any additional space must be added within the items +themselves. Any empty cells in the grid must be created by defining +placeholder items at the appropriate places in the grid definition. + +As with the \l Row and \l Column items, \l Grid items restrict the anchors +used by their child items. Since they position items both horizontally +and vertically, it is not possible to use any of the anchors to align +items within the grid. However, we can use placeholder items as the grid's +child items and put visible items inside those, using anchors to align +them. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-grid-positioning.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/grid-positioning.qml document start +\snippet examples/declarative/tutorials/qmlintro/grid-positioning.qml document end + +We only show the first item, but the principle is the same for the others. + +\clearfloat +\section3 Flow + +\l Flow items are used to place items like words on a page, with rows or +columns of non-overlapping items. + +Flow items arrange items in a similar way to \l Grid items, with items +arranged in lines along one axis (the minor axis), and lines of items +placed next to each other along another axis (the major axis). The +direction of flow, as well as the spacing between items, are controlled +by the \l{Flow::}{flow} and \l{Flow::}{spacing} properties. + +The following example shows a Flow item containing a number of \l Text +child items. These are arranged in a similar way to those shown in the +screenshots. + +\div {class="float-right"} +\inlineimage qml-flow-text1.png +\br +\inlineimage qml-flow-text2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/flow.qml document + +The main differences between the \l Grid and \l Flow positioners are that +items inside a \l Flow will wrap when they run out of space on the minor +axis, and items on one line may not be aligned with items on another line +if the items do not have uniform sizes. As with grid items, there is no +independent control of spacing between items and between lines of items. + +\clearfloat +\section2 Nesting Positioner Items + +Since each positioner is based on \l Item, we can nest them like other +items, placing one positioner inside another. The following example shows a +\l Column that contains two \l Row positioners. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-nested-positioners.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/nested-positioners.qml column + +The example works around the restrictions on the use of anchors mentioned +earlier by using appropriate anchors for each item. The innermost items, +\l Text and \l Rectangle, use anchors for vertical positioning within +\l Row items, which each perform horizontal positioning of their child +items. + +The rows use anchors to position themselves within the \l Column item, which +arranges them vertically. The column is centered horizontally and vertically +within its parent, a non-positioning item. + +\clearfloat +\section2 Strategies for Use + +Positioners are intended to be used in situations where it would be +tedious to apply anchors to a number of items. For this reason, they are +also used to position dynamically created items, such as those generated +by \l Repeater items. + +The items used with positioners must have a well-defined size, otherwise +positioners will not be able to determine where they should be placed, +leaving their positions undefined. When using a \l Column, it is sufficient +to give each child item a fixed height; the width can be defined using +anchors. Similarly, with a \l Row, the width of each item should be +fixed, but the height can be defined using anchors. Items used with \l Grid +and \l Flow positioners should have fixed widths and heights. +*/ + +/*! +\page qml-user-interaction.html +\contentspage Introduction to the QML Language +\previouspage Composing User Interfaces with QML +\nextpage Generating Items with Repeaters +\title User Interaction with QML +\brief Making items respond to user input. + +\tableofcontents + +So far, we have shown how to declare items and arrange them to create a user +interface. If we play a QML file using the \l{QML Viewer}, we can resize the +display window and see the items adapt to the change, but the items +themselves do not respond to user input from the keyboard or mouse. + +Unlike standard Qt widgets, items do not include intrinsic support for user +interaction. The features required for interactivity are added or applied to +items. + +QML provides the \l MouseArea item to handle mouse input and \l Keys and +\l KeyNavigation attached properties to handle keyboard input. These are +used with other items to make them responsive to user input. + +\section1 Mouse Areas + +To make items responsive to mouse clicks, we add \l MouseArea items to the +user interface, typically as children of the items we want to make +interactive. Since \l MouseArea is based on \l Item, it has a geometry, but +no visual appearance. The following example defines a mouse area with an +explicit position and size; the image shown indicates where the mouse area +is in the user interface, but it will not be visible in the running example. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-mousearea-annotated.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/mousearea.qml mouse area + +The \l{MouseArea::}{onPressed} and \l{MouseArea::}{onReleased} definitions +are \l{QML Concepts and Syntax#Signal Handlers}{signal handlers} that +contain JavaScript code that will be executed in response to a signal. In +this case, when the mouse button is pressed or released, the code will +change the color of the background. Other signal handlers can be defined +to handle other user input, such as \l{MouseArea::}{onClicked} and +\l{MouseArea::}{onDoubleClicked}. Some require additional configuration +of the item before they will work as expected, as we shall see later. + +\note It is more common to define mouse areas within items and position them +with anchors, as shown by the rest of the examples in this chapter. + +\clearfloat +\section2 Handling Mouse Buttons + +The following example uses an anchor to fill a \l Text item with a mouse +area, and defines two signal handlers to response to mouse button input. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-mouse-pressed1.png +\br +\inlineimage declarative-qmlintro-mouse-pressed2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/mouse-pressed-signals.qml text item + +The \l{MouseArea::}{onPressed} and \l{MouseArea::}{onReleased} +signal handlers are defined for the mouse area. As a result, when the user +presses a mouse button when the cursor is over the text, the color changes +to green; when the button is released, the color changes to black. + +Note that the mouse area only responds to the left mouse button by default. +This is because the default value of the \l{MouseArea::}{acceptedButtons} +is \l{Qt::LeftButton}{Qt.LeftButton}. To test for other buttons, set this +property to be the combination of the buttons required (using the OR +operator), as in the following example. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-mouse-pressed-buttons.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/mouse-pressed-buttons.qml items + +The mouse area covers the entire area of the user interface and accepts +input from both left and right buttons. Each of the rectangles defines its +color as an expression that depends on the mouse area's +\l{MouseArea::}{pressedButtons} property, testing whether the relevant +button is found in the value of this property. When a button is released, +the value is \c{Qt.NoButton}. + +\note The \l{MouseArea::}{pressed} property provides information about +whether or not a button was pressed in the mouse area, but does not +provide any more than a boolean value. This can be sufficient in many +situations. + +\clearfloat +\section2 Finding the Cursor Position + +The \l MouseArea item contains a number of properties and signal handlers +that provide information about the mouse cursor. For example, the +\l{MouseArea::}{mouseX} and \l{MouseArea::}{mouseY} properties contain the +position of the cursor, as shown in the following example. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-mouse-pressed-position.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/mouse-pressed-position.qml text item + +When the user presses the mouse button over the text item, the text changes +to show the coordinates within the mouse area where the press occurred. If +we need to find the mouse position outside the text item, we should make +the mouse area a child of the text item's parent and use anchors to fill +that item instead. + +\clearfloat +\section2 Mouse Hover + +In the previous examples, the text item and rectangles were updated only +when the mouse button was pressed. Consider a situation where we would like +to continuously update the text item with the mouse's position. In such a +case, we could try the following: + +\div {class="float-right"} +\inlineimage declarative-qmlintro-mouse-pressed-position2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/mouse-pressed-position2.qml text item + +When we run this example, the text item shows the initial, default value of +the mouse area's \c mouseX and \c mouseY properties. Moving the cursor over +the text has no effect. It is only when the text item is clicked that the +text is updated. + +The reason for this is that, by default, the mouse area only updates various +properties when a button is pressed. To receive continuous updates about the +mouse cursor, we need to enable \e{mouse hover} by setting its +\l{MouseArea::}{hoverEnabled} property, as shown in the following example: + +\div {class="float-right"} +\inlineimage declarative-qmlintro-mouse-hover-enabled.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/mouse-hover-enabled.qml text item + +With mouse hover enabled, other properties of the \l MouseArea can be +monitored. For example, the \l{MouseArea::}{containsMouse} property can be +used to determine whether the mouse cursor is over the mouse area. +Previously, we only knew when this was the case because the user had to +press a mouse button over the area. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-mouse-hover-containsmouse1.png +\br +\inlineimage declarative-qmlintro-mouse-hover-containsmouse2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/mouse-hover-containsmouse.qml items + +The above example uses \l{QML Concepts and Syntax#Expressions}{an expression} +to show the coordinates of the mouse cursor when it is in the mouse area, +\c area. When \c{area.containsMouse} evaluates to \c false, the \c{-} +character is shown instead. + +Certain signal handlers only become useful when mouse hover is enabled. +For example, the \l{MouseArea::}{onEntered}, \l{MouseArea::}{onExited} +and \l{MouseArea::}{onPositionChanged} signal handlers will be called +when the cursor enters, exits or changes position in the area. + +\section2 Dragging Items + +As well as handling the low level interaction details, the \l MouseArea item +also handles drag operations if the relevant properties are set. The +following example shows how dragging is enabled for an item. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-mouse-drag.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/mouse-drag.qml draggable item + +The item to be dragged is the \l Rectangle containing a \l MouseArea and +\l Text items. All that is required is to set the value of the +\l{MouseArea::}{drag.target} grouped property to the item we wish to enable +dragging for; in this case, the \c parent of the mouse area. When run, the +rectangle containing the text can be dragged around its parent's area. + +The other \c drag grouped properties allow the dragging behavior of the +item to be restricted and fine-tuned. \l{MouseArea::}{drag.axis} can be +set to only allow dragging to occur along the x or y axes, and the range +of positions to which the target item can be dragged can be limited to +a range specified by the \l{MouseArea::}{drag.minimumX}, +\l{MouseArea::}{drag.minimumY}, \l{MouseArea::}{drag.maximumX} and +\l{MouseArea::}{drag.maximumY} properties. + +\clearfloat +\section2 Strategies for Use + +Mouse areas are applied to a user interface by using anchors to fill the +items that need to respond to user input. This makes them responsive to +button presses by default, and to mouse movement when the +\l{MouseArea::}{hoverEnabled} property is set to \c true. When a mouse +area is not needed to provide input, its \l{MouseArea::}{enabled} +property can be set to \c false, so that it ignores user input. + +When mouse buttons are pressed and released, the +\l{MouseArea::}{pressedButtons} property is updated as expected. However, +when multiple buttons are used, as in the +\l{#Handling Mouse Buttons}{example above}, the most up-to-date values +reported by this property are not necessarily propagated to the items +that use it. For this reason, it can be better to consider using signal +handlers to respond to mouse button presses and releases. + + +\section1 Key Handling + +Another important method of user input is via the keyboard. In addition to +the \l TextInput and \l TextEdit items, which accept keyboard input for +display purposes, QML provides facilities to allow items to capture key +presses, as well as higher level features for navigation using keys. + +Unlike mouse input, which uses the \l MouseArea item, key input uses two +attached properties to handle keyboard input: \l Keys and \l KeyNavigation. +These look like ordinary elements, but can be applied to any item in order +to enable keyboard input support. + +\section2 Key Navigation + +In desktop user interfaces, it is usually helpful to provide a way for the +user to navigate between input fields or other interactive items by pressing +navigation keys, typically the cursor keys or the \key Tab key. The +\l KeyNavigation attached property is used to define the relationships +between items to allow this kind of navigation. + +The following example shows two \l Rectangle items placed in a \l Row +positioner. These are defined with identifiers, \c{leftRect} and +\c{rightRect}. + +\div {class="float-right"} +\inlineimage declarative-qmlintro-key-navigation1.png +\br +\inlineimage declarative-qmlintro-key-navigation2.png +\enddiv +\snippet examples/declarative/tutorials/qmlintro/key-navigation.qml items + +The \c{leftRect} rectangle attaches the +\l{KeyNavigation::right}{KeyNavigation.right} property, setting it to refer +to the \c{rightRect} rectangle. The \c{rightRect} rectangle attaches the +\l{KeyNavigation::left}{KeyNavigation.left} property, referring to the +\c{leftRect} rectangle. + +Initially, the \c{leftRect} rectangle has the keyboard focus, since its +\l{Item::}{focus} property is set to \c true. When the user presses the +right cursor key, the focus is passed to the \c{rightRect} rectangle instead, +as defined by the \l KeyNavigation attached property for that item. Pressing +the left cursor key causes the focus to be passed back to \c{leftRect} +because as defined by the \l KeyNavigation attached property for +\c{rightRect}. + +\clearfloat +*/ + +/*! +\page qml-positioning-items.html +\contentspage Introduction to the QML Language +\previouspage Composing User Interfaces with QML +\nextpage QML Tutorial +\title Generating Items with Repeaters +\brief How to generate and position items dynamically. + +\tableofcontents + +\section1 Repeaters + +\div {class="float-right"} +\inlineimage qml-repeater-grid-index.png +\enddiv + +Repeaters create items from a template for use with positioners, using data +from a model. Combining repeaters and positioners is an easy way to lay out +lots of items. A \l Repeater item is placed inside a positioner, and generates +items that the enclosing positioner arranges. + +Each Repeater creates a number of items by combining each element of data +from a model, specified using the \l{Repeater::model}{model} property, with +the template item, defined as a child item within the Repeater. +The total number of items is determined by the amount of data in the model. + +The following example shows a repeater used with a \l{#Grid}{Grid} item to +arrange a set of Rectangle items. The Repeater item creates a series of 24 +rectangles for the Grid item to position in a 5 by 5 arrangement. + +\clearfloat +\snippet doc/src/snippets/qml/repeaters/repeater-grid-index.qml document + +The number of items created by a Repeater is held by its \l{Repeater::}{count} +property. It is not possible to set this property to determine the number of +items to be created. Instead, as in the above example, we use an integer as +the model. This is explained in the \l{QML Data Models#An Integer}{QML Data Models} +document. + +It is also possible to use a delegate as the template for the items created +by a Repeater. This is specified using the \l{Repeater::}{delegate} property. + +\section1 Using Transitions + +Transitions can be used to animate items that are added to, moved within, +or removed from a positioner. + +Transitions for adding items apply to items that are created as part of a +positioner, as well as those that are reparented to become children of a +positioner. +Transitions for removing items apply to items within a positioner that are +deleted, as well as those that are removed from a positioner and given new +parents in a document. + +Additionally, changing the opacity of items to zero will cause them to +disappear using the remove transition, and making the opacity non-zero will +cause them to appear using the add transition. + +\section1 Other Ways to Position Items + +There are several other ways to position items in a user interface. In addition +to the basic technique of specifying their coordinates directly, they can be +positioned relative to other items with \l{anchor-layout}{anchors}, or used +with \l{QML Data Models} such as +\l{QML Data Models#VisualItemModel}{VisualItemModel}. +*/ |