C
Qt Quick Ultralite 列表模型示例
演示如何创建可变列表模型。
概述
本示例演示了如何使用 `Qul::ListModel` 创建可变模型。该模型在 `ListView ` 中用于构建一个最简报警应用程序。

该示例展示了一个可暂停、恢复和删除的闹钟列表。每次点击“Create new ”按钮,都会添加一个新的闹钟。
目标平台
项目结构
列表模型
mylistmodel.h文件定义了列表模型。
首先,它声明了列表元素的数据类型:
// To create a custom ListModel<T>, we need to declare a type T that holds // the data for each element and is equality comparable. // // Here, the data type is AlarmData and it holds the number of seconds before // the alarm should trigger (negative if it has already triggered), as well // as a running flag. //! [ListModel data] struct AlarmData { AlarmData() : seconds(0) , running(false) {} AlarmData(int argSeconds, bool argRunning) : seconds(argSeconds) , running(argRunning) {} int seconds; bool running; }; inline bool operator==(const AlarmData &lhs, const AlarmData &rhs) { return lhs.seconds == rhs.seconds && lhs.running == rhs.running; }
然后基于ListModel<AlarmData> 实现AlarmModel :
// Declare our AlarmModel. // // The only requirement is that we implement the pure virtual functions // count() and data() from ListModel. // // We add the other functions to allow our UI to affect the model. //! [custom ListModel] struct AlarmModel : Qul::ListModel<AlarmData> { private: Qul::DynamicList<AlarmData> m_data; public: // Implement the ListModel interface int count() const QUL_DECL_OVERRIDE { return m_data.count(); } AlarmData data(int index) const QUL_DECL_OVERRIDE { return m_data[index]; }
该模型还包含用于从 QML 修改模型的函数,例如 `addEntry() ` 函数。
void addEntry(int seconds) { m_data.append(AlarmData(seconds, true)); modelReset(); }
列表视图
listmodel.qml中的 `ListView ` 需要 `AlarmModel`,其实例作为根对象的子元素被创建:
// Create an instance of the custom AlarmModel AlarmModel { id: alarmModel }
ListView 函数使用模型实例为alarmDelegate 填充数据:
// This ListView is the main display element. It creates an alarmDelegate // instance for each entry in alarmModel and listens to alarmModel changes. ListView { width: parent.width anchors.top: parent.top anchors.bottom: controls.top model: alarmModel delegate: alarmDelegate }
当点击Create new 按钮时,会调用模型上的一个函数来添加一个新的闹钟:
Button { id: createNewButton text: "Create new" anchors.right: parent.right onClicked: alarmModel.addEntry(15) }
委托
委托根据模型中的数据控制ListView 中每个条目的外观和风格。
// Declare the delegate that the ListView (below) instantiates for each // entry in the alarm model. // // It shows information about the entry and two buttons, one to pause or // unpause the alarm, and one to remove it from the list. Component { id: alarmDelegate Item { width: root.width height: 60
例如,每个警报上按钮的状态和标签定义如下:
Row { anchors.right: parent.right Button { text: model.running ? "Pause" : "Unpause" visible: model.seconds > 0 // The "index" property contains the model index for // the current delegate instance. onClicked: alarmModel.togglePause(index) } Button { text: "Remove" onClicked: alarmModel.remove(index) } }
文件:
另请参阅《 Qul::ListModel 》 和《ListView 》。
在特定的 Qt 许可下提供。
了解更多信息。