ListView显示的数据来自于从内置的QML类型创建的模型,如ListModel和XmlListModel,或在C++中定义的继承于QAbstractItemModel或QAbstractListModel的自定义模型类。
ListView有一个模型,它定义了要显示的数据,还有一个委托,它定义了数据应该如何显示。列表视图中的项目是水平或垂直布置的。由于ListView继承了Flickable,所以ListView本质上是可弹出的。
下面的例子显示了一个简单的列表模型的定义,它被定义在一个叫做ContactModel.qml的文件中。
- import QtQuick 2.0
-
- ListModel {
- ListElement {
- name: "Bill Smith"
- number: "555 3264"
- }
- ListElement {
- name: "John Brown"
- number: "555 8426"
- }
- ListElement {
- name: "Sam Wise"
- number: "555 0473"
- }
- }
另一个组件可以在ListView中显示这个模型数据,像这样。
- import QtQuick 2.9
- import QtQuick.Window 2.2
-
- Window {
- visible: true
- width: 640
- height: 480
- title: qsTr("Hello World")
-
- ListView {
- width: 180; height: 200
-
- model: ContactModel {}
- delegate: Text {
- text: name + ": " + number
- }
- }
- }
在这里,ListView为其模型创建了一个ContactModel组件,为其委托创建了一个Text项目。视图将为模型中的每个项目创建一个新的Text组件。委托人能够直接访问模型的名字和号码数据。
运行效果如下:
下面是一个改进的列表视图。委托在视觉上得到了改进,并被移到一个单独的contactDelegate组件中。
- import QtQuick 2.9
- import QtQuick.Window 2.2
-
- Window {
- visible: true
- width: 640
- height: 480
- title: qsTr("Hello World")
-
- Rectangle {
- width: 180; height: 200
-
- Component {
- id: contactDelegate
- Item {
- width: 180; height: 40
- Column {
- Text { text: 'Name: ' + name }
- Text { text: 'Number: ' + number }
- }
- }
- }
-
- ListView {
- anchors.fill: parent
- model: ContactModel {}
- delegate: contactDelegate
- highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
- focus: true
- }
- }
- }
运行效果如下:

上面的代码使用了高亮属性highlight,当前选择的项目被蓝色的矩形高亮显示,焦点被设置为 "true",以启用列表视图的键盘导航。列表视图本身是一个焦点范围(更多细节见Qt Quick中的键盘焦点)。
代理根据需要被实例化,并且可以在任何时候被销毁。它们是ListView的contentItem的父对象,而不是视图本身。状态不应该被存储在一个委托中。
ListView将一些属性附加到委托的根项上,例如ListView.isCurrentItem。在下面的例子中,根委托项可以作为ListView.isCurrentItem直接访问这个附加属性,而子contactInfo对象必须作为wrapper.ListView.isCurrentItem引用这个属性。
- import QtQuick 2.9
- import QtQuick.Window 2.2
-
- Window {
- visible: true
- width: 640
- height: 480
- title: qsTr("Hello World")
-
- ListView {
- width: 180; height: 200
-
- Component {
- id: contactsDelegate
- Rectangle {
- id: wrapper
- width: 180
- height: contactInfo.height
- color: ListView.isCurrentItem ? "black" : "red"
- Text {
- id: contactInfo
- text: name + ": " + number
- color: wrapper.ListView.isCurrentItem ? "red" : "black"
- }
- }
- }
-
- model: ContactModel {}
- delegate: contactsDelegate
- focus: true
- }
- }
运行效果如下:

注意事项:
视图不会自动启用剪辑。如果视图没有被其他项目或屏幕剪掉,就有必要设置clip: true以使视图之外的项目被很好地剪掉。