天津商业网站建设,ui设计灵感网站,设计图软件,永康网站网站建设Fetch More Example这个例子说明了如何在视图模型上添加记录。 这个例子由一个对话框组成#xff0c;在Directory的输入框中#xff0c;可输入路径信息。应用程序会载入路径信息的文件信息等。不需要按回车键就能搜索。
当有大量数据时#xff0c;需要对视图模型进行批量增…Fetch More Example这个例子说明了如何在视图模型上添加记录。 这个例子由一个对话框组成在Directory的输入框中可输入路径信息。应用程序会载入路径信息的文件信息等。不需要按回车键就能搜索。
当有大量数据时需要对视图模型进行批量增加。
此案例实现了FileListModel类此类包含了一个视图模型这个视图模型获取路径下的文件。
下面来看下FileListModel的代码。 FileListModel Class Definition
FileListModel继承了QAbstractListModel并且存储了路径信息。只有视图自己请求添加项时才会进行添加。 class FileListModel : public QAbstractListModel{Q_OBJECTpublic:FileListModel(QObject *parent 0);int rowCount(const QModelIndex parent QModelIndex()) const override;QVariant data(const QModelIndex index, int role Qt::DisplayRole) const override;signals:void numberPopulated(int number);public slots:void setDirPath(const QString path);protected:bool canFetchMore(const QModelIndex parent) const override;void fetchMore(const QModelIndex parent) override;private:QStringList fileList;int fileCount;};比较关键的2个函数是fetchMore()和canFetchMore()这两个函数都是从QAbstractItemModel中继承下来的。当需要新增模型时这2个函数就会被触发。
setDirPath()函数设置了当前模型的工作目录。当需要批量设置模型时就会发出numberPopulated()信号。
所有文件条目都放到fileList里面fileCount统计条目的数量。 FileListModel Class Implementation
首先来看下setDirPath()。 void FileListModel::setDirPath(const QString path){QDir dir(path);beginResetModel();fileList dir.entryList();fileCount 0;endResetModel();}使用QDir获取目录内容。当要从模型中移除所有数据时需要通知QAbstractItemModel。 bool FileListModel::canFetchMore(const QModelIndex /* index */) const{if (fileCount fileList.size())return true;elsereturn false;}当需要更多项时canFetchMore()函数会被触发。当不需要新增时此函数返回true否则返回false。fetchMore()函数如下 void FileListModel::fetchMore(const QModelIndex /* index */){int remainder fileList.size() - fileCount;int itemsToFetch qMin(100, remainder);if (itemsToFetch 0)return;beginInsertRows(QModelIndex(), fileCount, fileCountitemsToFetch-1);fileCount itemsToFetch;endInsertRows();emit numberPopulated(itemsToFetch);}首先获取每一项的数量。beginInsertRow()和endInsertRow()在QAbstractItemModel中插入新行时必须要调用的最后emit numberPopulated()用于更新界面。
最后是rowCount()和data()
int FileListModel::rowCount(const QModelIndex /* parent */) const{return fileCount;}QVariant FileListModel::data(const QModelIndex index, int role) const{if (!index.isValid())return QVariant();if (index.row() fileList.size() || index.row() 0)return QVariant();if (role Qt::DisplayRole) {return fileList.at(index.row());} else if (role Qt::BackgroundRole) {int batch (index.row() / 100) % 2;if (batch 0)return qApp-palette().base();elsereturn qApp-palette().alternateBase();}return QVariant();}rowCount()函数是已经添加了的新行不是目录中的条目数。
data()函数从fileList中返回适当的条目。使用不同的背景颜色来区分。