StackView QML Type

Provides a stack-based navigation model. More...

Import Statement: import QtQuick.Controls 1.4
Since: Qt 5.1
Inherits:

FocusScope

Properties

Methods

Detailed Description

StackView implements a stack-based navigation model, which can be used with a set of interlinked information pages. Items are pushed onto the stack as the user navigates deeper into the material, and popped off again when he chooses to go back.

The touch gallery example is a good starting point to understand how StackView works. The following snippet from the example shows how it can be used:

StackView {
    id: stack
    initialItem: view

    Component {
        id: view

        MouseArea {
            Text {
                text: stack.depth
                anchors.centerIn: parent
            }
            onClicked: stack.push(view)
        }
    }
}

Using StackView in an Application

Using StackView in an application is typically a simple matter of adding the StackView as a child of a Window. The stack is usually anchored to the edges of the window, except at the top or bottom where it might be anchored to a status bar, or some other similar UI component. The stack can then be used by invoking its navigation methods. The first item to show in the StackView is the one that was assigned to initialItem.

Note: Items pushed onto the stack view have Stack attached properties.

Basic Navigation

There are three primary navigation operations in StackView: push(), pop(), and replace (replace by specifying argument replace to push()). These correspond to classic stack operations where "push" adds an item to the top of a stack, "pop" removes the top item from the stack, and "replace" is like a pop followed by a push, in that it replaces the topmost item on the stack with a new item (but the applied transtition might be different). The topmost item in the stack corresponds to the one that is currently visible on the screen. That means that "push" is the logical equivalent of navigating forward or deeper into the application, "pop" is the equivalent of navigating back, and "replace" is the equivalent of replacing the current item.

Sometimes it is necessary to go back more than a single step in the stack, for example, to return to a "main" item or some kind of section item in the application. For this use case, it is possible to specify an item as a parameter for pop(). This is called an "unwind" operation as the stack gets unwound to the specified item. If the item is not found, then the stack unwinds until there is only a single item in the stack, which then becomes the current item. To explicitly unwind to the bottom of the stack, it is recommended to use pop(null), though technically any non-existent item will do.

Given the stack [A, B, C]:

  • push(D) => [A, B, C, D] - "push" transition animation between C and D
  • pop() => [A, B] - "pop" transition animation between C and B
  • push(D, replace) => [A, B, D] - "replace" transition between C and D
  • pop(A) => [A] - "pop" transition between C and A

Note: When the stack is empty, a push() will not perform a transition animation because there is nothing to transition from (typically during application start-up). A pop() on a stack with depth 1 or 0 is a no-operation. If all items need to be removed from the stack, a separate function clear() is available.

Calling push() returns the item that was pushed onto the stack. Calling pop() returns the item that was popped off the stack. When pop() is called in an unwind operation, the top-most item (the first item that was popped, which will also be the one transitioning out) is returned.

Deep Linking

Deep linking means launching an application into a particular state. For example, a newspaper application could be launched into showing a particular article, bypassing the front item (and possibly a section item) that would normally have to be navigated through to get to the article concerned. In terms of StackView, deep linking means the ability to modify the state of the stack, so much so that it is possible to push a set of items to the top of the stack, or to completely reset the stack to a given state.

The API for deep linking in StackView is the same as for basic navigation. Pushing an array instead of a single item, will involve that all the items in that array will be pushed onto the stack. The transition animation, however, will be conducted as if only the last item in the array was pushed onto the stack. The normal semantics of push() apply for deep linking, meaning that push() adds whatever is pushed onto the stack. Note also that only the last item of the array will be loaded. The rest will be lazy-loaded as needed when entering the screen upon subsequent calls to pop (or when requesting the item by using get).

This gives us the following result, given the stack [A, B, C]:

Pushing items

An item pushed onto the StackView can be either an Item, a URL, a string containing a URL, or a Component. To push it, assign it to a property "item" inside a property list, and pass it as an argument to push:

stackView.push({item: yourItem})

The list can contain several properties that control how the item should be pushed:

  • item: this property is required, and holds the item to be pushed.
  • properties: a list of QML properties to be assigned to the item upon push. These properties will be copied into the item at load time, or when the item will become the current item (normally upon push).
  • immediate: set this property to true to skip transition effects. When pushing an array, this property only needs to be set on the first element to make the whole operation immediate.
  • replace: set this property to replace the current item on the stack. When pushing an array, you only need to set this property on the first element to replace as many elements on the stack as inside the array.
  • destroyOnPop: set this boolean to true if StackView needs to destroy the item when it is popped off the stack. By default (if destroyOnPop is not specified), StackView will destroy items pushed as components or URLs. Items not destroyed will be re-parented back to the original parents they had before being pushed onto the stack and hidden. If you need to set this property, do it with care, so that items are not leaked.

If the only argument needed is "item", the following short-hand notation can be applied:

stackView.push(yourItem)

You can push several items in one go by using an array of property lists. This is more efficient than pushing items one by one, as StackView can then load only the last item in the list. The rest will be loaded as they are about to become the current item (which happens when the stack is popped). The following example shows how to push an array of items:

stackView.push([{item: yourItem1}, {item: yourItem2}])

If an inline item is pushed, the item is temporarily re-parented into the StackView. When the item is later popped off, it gets re-parented back to its original owner again. If, however, an item is pushed as a component or a URL, the actual item will be created as an item from that component. This happens automatically when the item is about to become the current item in the stack. Ownership of the item will then normally be taken by the StackView, which will automatically destroy the item when it is later popped off. The component that declared the item, by contrast, remains in the ownership of the application and is not destroyed by the stack. This can be overridden by explicitly setting destroyOnPop in the list of arguments given to push.

If the properties to be pushed are specified, they will be copied into the item at loading time (in case of a component or URL), or when the item becomes the current item (in case of an inline item). The following example shows how this can be done:

stackView.push({item: someItem, properties: {fgcolor: "red", bgcolor: "blue"}})

Note: If an item is declared inside another item, and that parent gets destroyed, (even if a component was used), that child item will also be destroyed. This follows normal Qt parent-child destruction rules, but sometimes comes as a surprise for developers.

Lifecycle

An item's lifecycle in the StackView can have the following transitions:

  1. instantiation
  2. inactive
  3. activating
  4. active
  5. deactivating
  6. inactive
  7. destruction

It can move any number of times between inactive and active. When an item is activated, it's visible on the screen and is considered to be the current item. An item in a StackView that is not visible is not activated, even if the item is currently the top-most item in the stack. When the stack becomes visible, the item that is top-most gets activated. Likewise if the stack is then hidden, the topmost item would be deactivated. Popping the item off the top of the stack at this point would not result in further deactivation since the item is not active.

There is an attached Stack.status property that tracks the lifecycle. This property is an enumeration with the following values: Stack.Inactive, Stack.Activating, Stack.Active and Stack.Deactivating. Combined with the normal Component.onComplete and Component.onDestruction signals, the entire lifecycle is thus:

  • Created: Component.onCompleted()
  • Activating: Stack.onStatusChanged (Stack.status is Stack.Activating)
  • Acivated: Stack.onStatusChanged (Stack.status is Stack.Active)
  • Deactivating: Stack.onStatusChanged (Stack.status is Stack.Deactivating)
  • Deactivated: Stack.onStatusChanged (Stack.status is Stack.Inactive)
  • Destruction: Component.onDestruction()

Finding items

Sometimes it is necessary to search for an item, for example, in order to unwind the stack to an item to which the application does not have a reference. This is facilitated using a function find() in StackView. The find() function takes a callback function as its only argument. The callback gets invoked for each item in the stack (starting at the top). If the callback returns true, then it signals that a match has been found and the find() function returns that item. If the callback fails to return true (no match is found), then find() returns null.

The code below searches for an item in the stack that has a name "order_id" and then unwinds to that item. Note that since find() returns null if no item is found, and since pop unwinds to the bottom of the stack if null is given as the target item, the code works well even in case no matching item is found.

stackView.pop(stackView.find(function(item) {
    return item.name == "order_id";
}));

You can also get to an item in the stack using get(index). You should use this function if your item depends on another item in the stack, as the function will ensure that the item at the given index gets loaded before it is returned.

previousItem = stackView.get(myItem.Stack.index - 1));

Transitions

A transition is performed whenever a item is pushed or popped, and consists of two items: enterItem and exitItem. The StackView itself will never move items around, but instead delegates the job to an external animation set provided by the style or the application developer. How items should visually enter and leave the stack (and the geometry they should end up with) is therefore completely controlled from the outside.

When the transition starts, the StackView will search for a transition that matches the operation executed. There are three transitions to choose from: pushTransition, popTransition, and replaceTransition. Each implements how enterItem should animate in, and exitItem out. The transitions are collected inside a StackViewDelegate object assigned to delegate. By default, popTransition and replaceTransition will be the same as pushTransition, unless you set them to something else.

A simple fade transition could be implemented as:

StackView {
    delegate: StackViewDelegate {
        function transitionFinished(properties)
        {
            properties.exitItem.opacity = 1
        }

        pushTransition: StackViewTransition {
            PropertyAnimation {
                target: enterItem
                property: "opacity"
                from: 0
                to: 1
            }
            PropertyAnimation {
                target: exitItem
                property: "opacity"
                from: 1
                to: 0
            }
        }
    }
}

PushTransition needs to inherit from StackViewTransition, which is a ParallelAnimation that contains the properties enterItem and exitItem. These items should be assigned to the target property of animations within the transition. Since the same items instance can be pushed several times to a StackView, you should always override StackViewDelegate.transitionFinished(). Implement this function to reset any properties animated on the exitItem so that later transitions can expect the items to be in a default state.

A more complex example could look like the following. Here, the items are lying on the side before being rotated to an upright position:

StackView {
    delegate: StackViewDelegate {
        function transitionFinished(properties)
        {
            properties.exitItem.x = 0
            properties.exitItem.rotation = 0
        }

        pushTransition: StackViewTransition {
            SequentialAnimation {
                ScriptAction {
                    script: enterItem.rotation = 90
                }
                PropertyAnimation {
                    target: enterItem
                    property: "x"
                    from: enterItem.width
                    to: 0
                }
                PropertyAnimation {
                    target: enterItem
                    property: "rotation"
                    from: 90
                    to: 0
                }
            }
            PropertyAnimation {
                target: exitItem
                property: "x"
                from: 0
                to: -exitItem.width
            }
        }
    }
}

Advanced usage

When the StackView needs a new transition, it first calls StackViewDelegate.getTransition(). The base implementation of this function just looks for a property named properties.name inside itself (root), which is how it finds property Component pushTransition in the examples above.

function getTransition(properties)
{
    return root[properties.name]
}

You can override this function for your delegate if you need extra logic to decide which transition to return. You could for example introspect the items, and return different animations depending on the their internal state. StackView will expect you to return a Component that contains a StackViewTransition, or a StackViewTransition directly. The former is easier, as StackView will then create the transition and later destroy it when it's done, while avoiding any side effects caused by the transition being alive long after it has run. Returning a StackViewTransition directly can be useful if you need to write some sort of transition caching for performance reasons. As an optimization, you can also return null to signal that you just want to show/hide the items immediately without creating or running any transitions. You can also override this function if you need to alter the items in any way before the transition starts.

properties contains the properties that will be assigned to the StackViewTransition before it runs. In fact, you can add more properties to this object during the call if you need to initialize additional properties of your custom StackViewTransition when the returned component is instantiated.

The following example shows how you can decide which animation to use at runtime:

StackViewDelegate {
    function getTransition(properties)
    {
        return (properties.enterItem.Stack.index % 2) ? horizontalTransition : verticalTransition
    }

    function transitionFinished(properties)
    {
        properties.exitItem.x = 0
        properties.exitItem.y = 0
    }

    property Component horizontalTransition: StackViewTransition {
        PropertyAnimation {
            target: enterItem
            property: "x"
            from: target.width
            to: 0
            duration: 300
        }
        PropertyAnimation {
            target: exitItem
            property: "x"
            from: 0
            to: target.width
            duration: 300
        }
    }

    property Component verticalTransition: StackViewTransition {
        PropertyAnimation {
            target: enterItem
            property: "y"
            from: target.height
            to: 0
            duration: 300
        }
        PropertyAnimation {
            target: exitItem
            property: "y"
            from: 0
            to: target.height
            duration: 300
        }
    }
}

Supported Attached Properties

Items in a StackView support these attached properties:

Property Documentation

[read-only] busy : bool

busy is true if a transition is running, and false otherwise.


[read-only] currentItem : Item

The currently top-most item in the stack.


delegate : StackViewDelegate

The transitions to use when pushing or popping items. For better understanding on how to apply custom transitions, read Transitions.

See also Transitions.


[read-only] depth : int

The number of items currently pushed onto the stack.


initialItem : var

The first item that should be shown when the StackView is created. initialItem can take same value as the first argument to StackView.push(). Note that this is just a convenience for writing Component.onCompleted: stackView.push(myInitialItem)

Examples:

  • initialItem: Qt.resolvedUrl("MyItem.qml")
  • initialItem: myItem
  • initialItem: {"item" : Qt.resolvedUrl("MyRectangle.qml"), "properties" : {"color" : "red"}}

See also push.


Method Documentation

void clear()

Remove all items from the stack. No animations will be applied.


void completeTransition()

Immediately completes any ongoing transition. /sa Animation.complete


Item find(function, bool onlySearchLoadedItems = false)

Search for a specific item inside the stack. func will be called for each item in the stack (with the item as argument) until the function returns true. Return value will be the item found. For example: find(function(item, index) { return item.isTheOne }) Set onlySearchLoadedItems to true to not load items that are not loaded into memory


Item get(int index, bool dontLoad = false)

Returns the item at position index in the stack. If dontLoad is true, the item will not be forced to load (and null will be returned if not yet loaded)


Item pop(Item item = undefined)

Pops one or more items off the stack.

The function can also take a property list as argument - Item StackView::pop(jsobject dict), which can contain one or more of the following properties:

  • item: if specified, all items down to (but not including) item will be popped off. If item is null, all items down to (but not including) the first item will be popped. If not specified, only the current item will be popped.
  • immediate: set this property to true to skip transition effects.

Examples:

Note: If the only argument needed is "item", you can apply the following short- hand notation: stackView.pop(anItem).

Returns the item that was popped off

See also clear().


Item push(Item item)

Pushes an item onto the stack.

The function can also take a property list as argument - Item StackView::push(jsobject dict), which should contain one or more of the following properties:

  • item: this property is required, and holds the item you want to push.
  • properties: a list of QML properties that should be assigned to the item upon push. These properties will be copied into the item when it is loaded (in case of a component or URL), or when it becomes the current item for the first time (normally upon push).
  • immediate: set this property to true to skip transition effects. When pushing an array, you only need to set this property on the first element to make the whole operation immediate.
  • replace: set this property to replace the current item on the stack. When pushing an array, you only need to set this property on the first element to replace as many elements on the stack as inside the array.
  • destroyOnPop: set this property to specify if the item needs to be destroyed when its popped off the stack. By default (if destroyOnPop is not specified), StackView will destroy items pushed as components or URLs. Items not destroyed will be re-parented to the original parents they had before being pushed onto the stack, and hidden. If you need to set this property, do it with care, so that items are not leaked.

You can also push an array of items (property lists) if you need to push several items in one go. A transition will then only occur between the current item and the last item in the list. Loading the other items will be deferred until needed.

Examples:

  • stackView.push({item:anItem})
  • stackView.push({item:aURL, immediate: true, replace: true})
  • stackView.push({item:aRectangle, properties:{color:"red"}})
  • stackView.push({item:aComponent, properties:{color:"red"}})
  • stackView.push({item:aComponent.createObject(), destroyOnPop:true})
  • stackView.push([{item:anitem, immediate:true}, {item:aURL}])

Note: If the only argument needed is "item", you can apply the following short- hand notation: stackView.push(anItem).

Returns the item that became current.

See also initialItem and Pushing items.


© 2017 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.