当前位置: 代码迷 >> 综合 >> Quick控件--9.listmodel:FolderListModel
  详细解决方案

Quick控件--9.listmodel:FolderListModel

热度:4   发布时间:2023-12-28 14:33:56.0

Quick控件--9.listmodel:FolderListModel

  • 1 效果
  • 2 介绍
    • 2.1 来自《Mastering Qt 5 2nd》
      • Qt提供的各种Model子类的都继承QAbstractItemModel。在开始示例化之前,需要选择继承的基类。
      • QAbstractListModel继承类的需要重写读写接口
      • 使用步骤
      • 在data()的实现中设置index参数对应的返回内容
      • roleNames()函数
      • 数据修改
  • 3 控件代码
  • 参考

直接使用Qt.labs.folderlistmodel,只能显示已经注册到qml.qrc中的文件,这就导致该功能很局限,要使用得自己写model

1 效果

2 介绍

实现QAbstractListModel必须要实现以下三个虚函数,并且在自定义的模型类中给出用于存储数据的数据结构。

int rowCount(const QModelIndex& parent=QModelIndex())//用来给出模型中项的个数
QVarient data(cosnt QModelIndex& index,int role=Qt::QDisplayRole) const//返回相应的数据
QHash<int,QByteArray> roleNames() const//为了在QML中通过别名来使用数据

2.1 来自《Mastering Qt 5 2nd》

Qt提供的各种Model子类的都继承QAbstractItemModel。在开始示例化之前,需要选择继承的基类。

  • QAbstractItemModel:最底层,最抽象,更具拓展性。
  • QStringListModel:处理string给视图,简单。
  • QSqlTableModel:负责处理数据库的。
  • QAbstractListModel:提供一维列表model

QAbstractListModel继承类的需要重写读写接口

  • rowCount(): 获取列表大小
  • data(): 获取要显示信息的
  • roleNames(): 显示框架中每个role的名字
  • setData(): 用于更新数据
  • removeRows(): 用于删除数据

使用步骤

1、知道要显示在界面上数据的数量,接口为rowCount()

int Class::rowCount(const QModelIndex& parent) const
{return size;
}

The rowCount() function has an unknown parameter: const QModelIndex& parent. Here, it is not used,
The QModelIndex class is a central concept of the Model/View framework in Qt. It
is a lightweight object used to locate data within a model.
在这里插入图片描述
List Model: Data is stored in a one-dimensional array (rows)
Table Model: Data is stored in a two-dimensional array (rows and columns)
Tree Model: Data is stored in a hierarchical relationship (parent/children)
处理所有这些model类型,Qt设计了QModelIndex这个类。
QModelIndex类为这些用例提供了函数如下row(), column(), and parent()/child().
该模型将根据其数据类型生成索引并提供这些索引,索引到视图。 然后,视图将使用它们来查询新数据到模型,而无需知道index.row()函数是否对应到数据库行或vector索引。

在data()的实现中设置index参数对应的返回内容

view通过index和role请求数据,重写了index后,只需要关注role就行。
数据显示时,可能是多个信息。role为了让view对应的数据部分,使用flag(enum),
关联每个数据元素
Qt提供各种默认的role(DisplayRole, DecorationRole, EditRole, and so on)
可以根据需要自己定义

roleNames()函数

在抽象层,view要显示什么信息并不清楚,roleNames()函数便是为了应对这样的需求,
以便可以通过QML访问角色名称。

数据修改

beginInsertRows()和endInsertRows()触发相应的信号
beginInsertRows(): 通知view,新行插入给定的索引
endInsertRows(): 通知view,新行已经插入给定的索引

3 控件代码

参考

1、QML - 小例子 - 文件目录浏览器
2、Qt Quick之ListView下拉刷新数据
3、QML的学习与应用:读取本地文件夹下的文件并通过列表显示
4、QT QML目录导航列表视图
5、FolderListModel QML Type

  相关解决方案