Qt Reference Documentation

- Qt 4.8
- ALL VERSIONS

- A
- A
- A
- Print

Animation and Transitions Presenting Data with Views

# QML Data Models

QML items such as ListView, GridView and Repeater require Data Models that provide the data to be displayed. These items typically require a delegate component that creates an instance for each item in the model. Models may be static, or have items modified, inserted, removed or moved dynamically.

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:

     import QtQuick 1.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
         }
     }

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 element 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 QStringList model 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.

QML provides several types of data models among the built-in set of QML elements. In addition, models can be created with C++ and then made available to QML components.

The views used to access data models are described in the Presenting Data with Views overview. The use of positioner items to arrange items from a model is covered in Using QML Positioner and Repeater Items.

## QML Data Models

### ListModel

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

     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 ListView delegate, for example:

     ListView {
         anchors.fill: parent
         model: fruitModel
         delegate: Row {
             Text { text: "Fruit: " + name }
             Text { text: "Cost: $" + cost }
         }
     }

ListModel provides methods to manipulate the ListModel directly via JavaScript. In this case, the first item inserted determines the roles available to any views that are using the model. For example, if an empty ListModel is created and populated via JavaScript, the roles provided by the first insertion are the only roles that will be shown in the view:

     ListModel { id: fruitModel }
         ...
     MouseArea {
         anchors.fill: parent
         onClicked: fruitModel.append({"cost": 5.95, "name":"Pizza"})
     }

When the MouseArea is clicked, `fruitModel` will have two roles, cost and name. Even if subsequent roles are added, only the first two will be handled by views using the model. To reset the roles available in the model, call ListModel::clear().

### XmlListModel

XmlListModel allows construction of a model from an XML data source. The roles are specified via the XmlRole element.

The following model has three roles, title, link and description:

     XmlListModel {
          id: feedModel
          source: "http://rss.news.yahoo.com/rss/oceania"
          query: "/rss/channel/item"
          XmlRole { name: "title"; query: "title/string()" }
          XmlRole { name: "link"; query: "link/string()" }
          XmlRole { name: "description"; query: "description/string()" }
     }

The RSS News demo shows how XmlListModel can be used to display an RSS feed.

### VisualItemModel

VisualItemModel allows QML items to be provided as a model.

This model contains both the data and delegate; the child items of a VisualItemModel provide the contents of the delegate. The model does not provide any roles.

     VisualItemModel {
         id: itemModel
         Rectangle { height: 30; width: 80; color: "red" }
         Rectangle { height: 30; width: 80; color: "green" }
         Rectangle { height: 30; width: 80; color: "blue" }
     }

     ListView {
         anchors.fill: parent
         model: itemModel
     }

Note that in the above example there is no delegate required. The items of the model itself provide the visual elements that will be positioned by the view.

## C++ Data Models

Models can be defined in C++ and then made available to QML. This is useful for exposing existing C++ data models or otherwise complex datasets to QML.

A C++ model class can be defined as a QStringList, a QList<QObject*> or a QAbstractItemModel. The first two are useful for exposing simpler datasets, while QAbstractItemModel provides a more flexible solution for more complex models.

### QStringList-based model

A model may be a simple QStringList, which provides the contents of the list via the modelData role.

Here is a ListView with a delegate that references its model item's value using the `modelData` role:

A Qt application can load this QML document and set the value of `myModel` to a QStringList:

         QStringList dataList;
         dataList.append("Item 1");
         dataList.append("Item 2");
         dataList.append("Item 3");
         dataList.append("Item 4");

         QDeclarativeContext *ctxt = viewer.rootContext();
         ctxt->setContextProperty("myModel", QVariant::fromValue(dataList));

The complete example is available in Qt's examples/declarative/modelviews/stringlistmodel directory.

Note: There is no way for the view to know that the contents of a QStringList have changed. If the QStringList changes, it will be necessary to reset the model by calling QDeclarativeContext::setContextProperty() again.

### QObjectList-based model

A list of QObject* values can also be used as a model. A QList<QObject*> provides the properties of the objects in the list as roles.

The following application creates a `DataObject` class that with Q_PROPERTY values that will be accessible as named roles when a QList<DataObject*> is exposed to QML:

     class DataObject : public QObject
     {
         Q_OBJECT

         Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
         Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged)
         ...
     };

     int main(int argc, char ** argv)
     {
         QApplication app(argc, argv);
         QmlApplicationViewer viewer;

         QList<QObject*> dataList;
         dataList.append(new DataObject("Item 1", "red"));
         dataList.append(new DataObject("Item 2", "green"));
         dataList.append(new DataObject("Item 3", "blue"));
         dataList.append(new DataObject("Item 4", "yellow"));

         QDeclarativeContext *ctxt = viewer.rootContext();
         ctxt->setContextProperty("myModel", QVariant::fromValue(dataList));
         ...

The QObject* is available as the `modelData` property. As a convenience, the properties of the object are also made available directly in the delegate's context. Here, `view.qml` references the `DataModel` properties in the ListView delegate:

Note the use of the fully qualified access to the `color` property. The properties of the object are not replicated in the `model` object, since they are easily available via the `modelData` object.

The complete example is available in Qt's examples/declarative/modelviews/objectlistmodel directory.

Note: There is no way for the view to know that the contents of a QList have changed. If the QList changes, it will be necessary to reset the model by calling QDeclarativeContext::setContextProperty() again.

### QAbstractItemModel

A model can be defined by subclassing QAbstractItemModel. This is the best approach if you have a more complex model that cannot be supported by the other approaches. A QAbstractItemModel can also automatically notify a QML view when the model data has changed.

The roles of a QAbstractItemModel subclass can be exposed to QML by calling QAbstractItemModel::setRoleNames(). The default role names set by Qt are:

Qt Role | QML Role Name
--- | ---
Qt::DisplayRole | display
Qt::DecorationRole | decoration

Here is an application with a QAbstractListModel subclass named `AnimalModel` that has type and size roles. It calls QAbstractItemModel::setRoleNames() to set the role names for accessing the properties via QML:

     class Animal
     {
     public:
         Animal(const QString &type, const QString &size);
         ...
     };

     class AnimalModel : public QAbstractListModel
     {
         Q_OBJECT
     public:
         enum AnimalRoles {
             TypeRole = Qt::UserRole + 1,
             SizeRole
         };

         AnimalModel(QObject *parent = 0);
         ...
     };

     AnimalModel::AnimalModel(QObject *parent)
         : QAbstractListModel(parent)
     {
         QHash<int, QByteArray> roles;
         roles[TypeRole] = "type";
         roles[SizeRole] = "size";
         setRoleNames(roles);
     }

     int main(int argc, char ** argv)
     {
         QApplication app(argc, argv);
         QmlApplicationViewer viewer;

         AnimalModel model;
         model.addAnimal(Animal("Wolf", "Medium"));
         model.addAnimal(Animal("Polar bear", "Large"));
         model.addAnimal(Animal("Quoll", "Small"));

         QDeclarativeContext *ctxt = viewer.rootContext();
         ctxt->setContextProperty("myModel", &model);
         ...

This model is displayed by a ListView delegate that accesses the type and size roles:

QML views are automatically updated when the model changes. Remember the model must follow the standard rules for model changes and notify the view when the model has changed by using QAbstractItemModel::dataChanged(), QAbstractItemModel::beginInsertRows(), etc. See the Model subclassing reference for more information.

The complete example is available in Qt's examples/declarative/modelviews/abstractitemmodel directory.

QAbstractItemModel presents a hierarchy of tables, but the views currently provided by QML can only display list data. In order to display child lists of a hierarchical model the VisualDataModel element provides several properties and functions for use with models of type QAbstractItemModel:

- hasModelChildren role property to determine whether a node has child nodes.
- VisualDataModel::rootIndex allows the root node to be specifed
- VisualDataModel::modelIndex() returns a QModelIndex which can be assigned to VisualDataModel::rootIndex
- VisualDataModel::parentModelIndex() returns a QModelIndex which can be assigned to VisualDataModel::rootIndex

### Exposing C++ Data Models to QML

The above examples use QDeclarativeContext::setContextProperty() to set model values directly in QML components. An alternative to this is to register the C++ model class as a QML type from a QML C++ plugin using QDeclarativeExtensionPlugin. This would allow the model classes to be created directly as elements within QML:

     class MyModelPlugin : public QDeclarativeExtensionPlugin
     {
     public:
         void registerTypes(const char *uri)
         {
             qmlRegisterType<MyModel>(uri, 1, 0,
                     "MyModel");
         }
     }

     Q_EXPORT_PLUGIN2(mymodelplugin, MyModelPlugin);
     MyModel {
         id: myModel
         ListElement { someProperty: "some value" }
     }
     ListView {
         width: 200; height: 250
         model: myModel
         delegate: Text { text: someProperty }
     }

See Tutorial: Writing QML extensions with C++ for details on writing QML C++ plugins.

## Other Data Models

### An Integer

An integer can be used to specify a model that contains a certain number of elements. In this case, the model does not have any data roles.

The following example creates a ListView with five elements:

     Item {
         width: 200; height: 250

         Component {
             id: itemDelegate
             Text { text: "I am item number: " + index }
         }

         ListView {
             anchors.fill: parent
             model: 5
             delegate: itemDelegate
         }

     }

### An Object Instance

An object instance can be used to specify a model with a single object element. The properties of the object are provided as roles.

The example below creates a list with one item, showing the color of the myText text. Note the use of the fully qualified model.color property to avoid clashing with color property of the Text element in the delegate.

     Rectangle {
         width: 200; height: 250

         Text {
             id: myText
             text: "Hello"
             color: "#dd44ee"
         }

         Component {
             id: myDelegate
             Text { text: model.color }
         }

         ListView {
             anchors.fill: parent
             anchors.topMargin: 30
             model: myText
             delegate: myDelegate
         }
     }

## Accessing Views and Models from Delegates

You can access the view for which a delegate is used, and its properties, by using ListView.view in a delegate on a ListView, or GridView.view in a delegate on a GridView, etc. In particular, you can access the model and its properties by using ListView.view.model.

This 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.

     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
         }
     }

Another important case is when some action (e.g. mouse click) in the delegate should update data in the model. In this case you can define a function in the model, e.g.:

             setData(int row, const QString & field_name, QVariant new_value),

...and call it from the delegate using:

             ListView.view.model.setData(index, field, value)

...assuming that field holds the name of the field which should be updated, and that value holds the new value.

Animation and Transitions Presenting Data with Views