Using the ListView with a model


This post explains shortly how to use a ListView with a simple model and a delegate to paint the model data.

To display a content in a ListView you need a model (e.g. ListModel) and a delegate (a Component).
The model contains the data to be displayed, the delegate knows how to paint each model element.
The ListView provides a flickable area, which lays out the elements in a vertical line.

import Qt 4.6

Rectangle {
  width: 200; height: 200

  Component {
    id: delegate
    Item {
      width: 200; height: 28
      Text {
        text: title
      }
    }
  }

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

  ListModel {
    id: model
    ListElement { title: "Germany" }
    ListElement { title: "France" }
    ListElement { title: "Italy" }
    ListElement { title: "United Kingdom" }
  }
}

The ListView can also have a horizontal orientation or a highlighter component. The delegate is bound to the model by the model element names (here title).

Besides the ListModel there is also a XmlListModel and a VisualItemModel. The XmlListModel get’s the data from an Xml content (e.g. RSS feed) and selects the right parts based on a XPath query. The VisualItemModel contains data and delegate. A good coverage of model data can be found here.

Here a more complex example:

import Qt 4.6

Rectangle {
  id: container
  width: 200; height: 200
  Component {
    id: delegate
    Item {
      width: 200; height: 28
      Text {
        x: 8
        text: title
        anchors.verticalCenter: parent.verticalCenter
      }
      Rectangle {
        height: 12; width: population;
        anchors.right: parent.right
        anchors.verticalCenter: parent.verticalCenter
        color: "lightsteelblue"
      }
    }

  }

  ListView {
    id: view
    anchors.fill: parent
    model: model
    delegate: delegate
  }

  ListModel {
    id: model
    ListElement {
      title: "Germany"
      population: 81
    }
    ListElement {
      title: "France"
      population: 65
    }
    ListElement {
      title: "Italy"
      population: 60
    }
    ListElement {
      title: "United Kingdom"
      population: 62
    }
  }
}

The delegate now display a horizontal bar, based on the population of the country.

Here the screenshot to the example:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s