Models and Views in Qt Quick

Simply put, applications need to form data and display the data. Qt Quick has the notion of models, views, and delegates to display data. They modularize the visualization of data in order to give the developer or designer control over the different aspects of the data. A developer can swap a list view with a grid view with little changes to the data. Similarly, encapsulating an instance of the data in a delegate allows the developer to dictate how to present or handle the data.

Image non disponible
  • Model - contains the data and its structure. There are several QML types for creating models.

  • View - a container that displays the data. The view might display the data in a list or a grid.

  • Delegate - dictates how the data should appear in the view. The delegate takes each data in the model and encapsulates it. The data is accessible through the delegate. The delegate can also write data back into editable models (e.g. in a TextField's onAccepted Handler).

To visualize data, bind the view's model property to a model and the delegate property to a component or another compatible type.

Displaying Data with Views

Views are containers for collections of items. They are feature-rich and can be customizable to meet style or behavior requirements.

A set of standard views are provided in the basic set of Qt Quick graphical types:

  • ListView - arranges items in a horizontal or vertical list

  • GridView - arranges items in a grid within the available space

  • PathView - arranges items on a path

These types have properties and behaviors exclusive to each type. Visit their respective documentation for more information.

Decorating Views

Views allow visual customization through decoration properties such as the header, footer, and section properties. By binding an object, usually another visual object, to these properties, the views are decoratable. A footer may include a Rectangle type showcasing borders or a header that displays a logo on top of the list.

Suppose that a specific club wants to decorate its members list with its brand colors. A member list is in a model and the delegate will display the model's content.

 
Sélectionnez
ListModel {
    id: nameModel
    ListElement { name: "Alice" }
    ListElement { name: "Bob" }
    ListElement { name: "Jane" }
    ListElement { name: "Harry" }
    ListElement { name: "Wendy" }
}
Component {
    id: nameDelegate
    Text {
        text: name;
        font.pixelSize: 24
    }
}

The club may decorate the members list by binding visual objects to the header and footer properties. The visual object may be defined inline, in another file, or in a Component type.

 
Sélectionnez
ListView {
    anchors.fill: parent
    clip: true
    model: nameModel
    delegate: nameDelegate
    header: bannercomponent
    footer: Rectangle {
        width: parent.width; height: 30;
        gradient: clubcolors
    }
    highlight: Rectangle {
        width: parent.width
        color: "lightgray"
    }
}

Component {     //instantiated when header is processed
    id: bannercomponent
    Rectangle {
        id: banner
        width: parent.width; height: 50
        gradient: clubcolors
        border {color: "#9EDDF2"; width: 2}
        Text {
            anchors.centerIn: parent
            text: "Club Members"
            font.pixelSize: 32
        }
    }
}
Gradient {
    id: clubcolors
    GradientStop { position: 0.0; color: "#8EE2FE"}
    GradientStop { position: 0.66; color: "#7ED2EE"}
}
Image non disponible

Mouse and Touch Handling

The views handle dragging and flicking of their content, however they do not handle touch interaction with the individual delegates. In order for the delegates to react to touch input, e.g. to set the currentIndex, a MouseArea with the appropriate touch handling logic must be provided by the delegate.

Note that if highlightRangeMode is set to StrictlyEnforceRange the currentIndex will be affected by dragging/flicking the view, since the view will always ensure that the currentIndex is within the highlight range specified.

ListView Sections

ListView contents may be grouped into sections, where related list items are labeled according to their sections. Further, the sections may be decorated with delegates.

A list may contain a list indicating people's names and the team on which team the person belongs.

 
Sélectionnez
ListModel {
    id: nameModel
    ListElement { name: "Alice"; team: "Crypto" }
    ListElement { name: "Bob"; team: "Crypto" }
    ListElement { name: "Jane"; team: "QA" }
    ListElement { name: "Victor"; team: "QA" }
    ListElement { name: "Wendy"; team: "Graphics" }
}
Component {
    id: nameDelegate
    Text {
        text: name;
        font.pixelSize: 24
        anchors.left: parent.left
        anchors.leftMargin: 2
    }
}

The ListView type has the section attached property that can combine adjacent and related types into a section. The section.property determines which list type property to use as sections. The section.criteria can dictate how the section names are displayed and the section.delegate is similar to the views' delegate property.

 
Sélectionnez
ListView {
    anchors.fill: parent
    model: nameModel
    delegate: nameDelegate
    focus: true
    highlight: Rectangle {
        color: "lightblue"
        width: parent.width
    }
    section {
        property: "team"
        criteria: ViewSection.FullString
        delegate: Rectangle {
            color: "#b0dfb0"
            width: parent.width
            height: childrenRect.height + 4
            Text { anchors.horizontalCenter: parent.horizontalCenter
                font.pixelSize: 16
                font.bold: true
                text: section
            }
        }
    }
}
Image non disponible
 

View Delegates

Views need a delegate to visually represent an item in a list. A view will visualize each item list according to the template defined by the delegate. Items in a model are accessible through the index property as well as the item's properties.

 
Sélectionnez
Component {
    id: petdelegate
    Text {
        id: label
        font.pixelSize: 24
        text: index === 0 ? type + " (default)" : type

        required property int index
        required property string type
    }
}
Image non disponible

Accessing Views and Models from Delegates

The list view to which the delegate is bound is accessible from the delegate through the ListView.view property. Likewise, the GridView GridView.view is available to delegates. The corresponding model and its properties, therefore, are available through ListView.view.model. In addition, any defined signals or methods in the model are also accessible.

This mechanism is useful when you want to use the same delegate for a number of views, for example, but you want decorations or other features to be different for each view, and you would like these different settings to be properties of each of the views. Similarly, it might be of interest to access or show some properties of the model.

In the following example, the delegate shows the property language of the model, and the color of one of the fields depends on the property fruit_color of the view.

 
Sélectionnez
Rectangle {
     width: 200; height: 200

    ListModel {
        id: fruitModel
        property string language: "en"
        ListElement {
            name: "Apple"
            cost: 2.45
        }
        ListElement {
            name: "Orange"
            cost: 3.25
        }
        ListElement {
            name: "Banana"
            cost: 1.95
        }
    }

    Component {
        id: fruitDelegate
        Row {
                id: fruit
                Text { text: " Fruit: " + name; color: fruit.ListView.view.fruit_color }
                Text { text: " Cost: $" + cost }
                Text { text: " Language: " + fruit.ListView.view.model.language }
        }
    }

    ListView {
        property color fruit_color: "green"
        model: fruitModel
        delegate: fruitDelegate
        anchors.fill: parent
    }
}
 

Models

Data is provided to the delegate via named data roles which the delegate may bind to. Here is a ListModel with two roles, type and age, and a ListView with a delegate that binds to these roles to display their values:

 
Sélectionnez
import QtQuick 2.0

Item {
    width: 200; height: 250

    ListModel {
        id: myModel
        ListElement { type: "Dog"; age: 8 }
        ListElement { type: "Cat"; age: 5 }
    }

    Component {
        id: myDelegate
        Text { text: type + ", " + age }
    }

    ListView {
        anchors.fill: parent
        model: myModel
        delegate: myDelegate
    }
}

To get finer control over which roles are accessible, and to make delegates more self-contained and usable outside of views, required properties can be used. If a delegate contains required properties, the named roles are not provided. Instead, the QML engine will check if the name of a required property matches that of a model role. If so, that property will be bound to the corresponding value from the model.

 
Sélectionnez
import QtQuick 2.0

Item {
    width: 200
    height: 250

    ListModel {
        id: myModel
        ListElement { type: "Dog"; age: 8; noise: "meow" }
        ListElement { type: "Cat"; age: 5; noise: "woof" }
    }

    component MyDelegate : Text {
        required property string type
        required property int age
        text: type + ", " + age
        // WRONG: Component.onCompleted: () => console.log(noise)
        // The above line would cause a ReferenceError
        // as there is no required property noise,
        // and the presence of the required properties prevents
        // noise from being injected into the scope
    }

    ListView {
        anchors.fill: parent
        model: myModel
        delegate: MyDelegate {}
    }
}

If there is a naming clash between the model's properties and the delegate's properties, the roles can be accessed with the qualified model name instead. For example, if a Text type had type or age properties, the text in the above example would display those property values instead of the type and age values from the model item. In this case, the properties could have been referenced as model.type and model.age instead to ensure the delegate displays the property values from the model item.

A special index role containing the index of the item in the model is also available to the delegate. Note this index is set to -1 if the item is removed from the model. If you bind to the index role, be sure that the logic accounts for the possibility of index being -1, i.e. that the item is no longer valid. (Usually the item will shortly be destroyed, but it is possible to delay delegate destruction in some views via a delayRemove attached property.)

Models that do not have named roles (such as the ListModel shown below) will have the data provided via the modelData role. The modelData role is also provided for models that have only one role. In this case the modelData role contains the same data as the named role.

model, index, and modelData roles are not accessible if the delegate contains required properties, unless it has also required properties with matching names.

QML provides several types of data models among the built-in set of QML types. In addition, models can be created with Qt C++ and then made available to QQmlEngine for use by QML components. For information about creating these models, visit the Using C++ Models with Qt Quick Views and creating QML types articles.

Positioning of items from a model can be achieved using a Repeater.

List Model

ListModel is a simple hierarchy of types specified in QML. The available roles are specified by the ListElement properties.

 
Sélectionnez
ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        cost: 1.95
    }
}

The above model has two roles, name and cost. These can be bound to by a