一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

一.定义
  Qt提供了QFileSystemModel类,用于在Qt应用程序中展示文件系统的数据。QFileSystemModel类是QAbstractItemModel的子类,可以方便地将文件系统的文件和文件夹结构作为数据模型,供Qt的视图类(比如QTreeView、QListView等)使用。

二.功能

  1. 设置根路径:使用setRootPath()方法设置文件系统的根路径。
  2. 获取文件和文件夹信息:使用rowCount()和data()方法来获取文件和文件夹的信息,比如文件名、文件大小、文件类型等。
  3. 获取文件索引:使用index()方法获取文件或文件夹在模型中的索引。
  4. 监听文件系统变化:使用directoryLoaded()信号来监听文件系统目录加载完成的信号,directoryChanged()信号来监听文件系统目录变化的信号。
  5. 排序和过滤:可以使用sort()方法进行排序,setNameFilters()方法来过滤文件类型。

三.代码示例

 1 #include <QApplication>
 2 #include <QTreeView>
 3 #include <QFileSystemModel>
 4 #include <QDir>
 5 #include <QDebug>
 6  
 7 int main(int argc, char *argv[])
 8 {
 9     QApplication a(argc, argv);
10     
11     // 创建一个QFileSystemModel对象
12     QFileSystemModel model;
13     
14     // 设置文件系统的根路径为当前工作目录
15     QString rootPath = QDir::currentPath();
16     model.setRootPath(rootPath);
17     
18     // 创建一个QTreeView对象,并将QFileSystemModel设置为其模型
19     QTreeView treeView;
20     treeView.setModel(&model);
21     
22     // 设置QTreeView的根索引为模型的根目录索引
23     QModelIndex rootIndex = model.index(rootPath);
24     treeView.setRootIndex(rootIndex);
25  
26     // 打印根路径下的子文件和子文件夹名
27     int rowCount = model.rowCount(rootIndex);
28     for (int i = 0; i < rowCount; ++i) {
29         QModelIndex childIndex = model.index(i, 0, rootIndex);
30         QString childName = model.fileName(childIndex);
31         qDebug() << "Child Name:" << childName;
32     }
33  
34     treeView.setWindowTitle("File System Viewer");
35     treeView.show();
36     
37     return a.exec();
38 }

四.模型索引介绍
  在Qt中,数据模型(例如QFileSystemModel)中的索引是用来标识模型中的特定数据项(如文件、文件夹等)的对象。索引由两个主要部分组成:行号和列号。在一维数据模型中,索引只包含行号,而在二维数据模型中,索引包含行号和列号。

  索引可以通过模型的index()方法来创建,该方法接受行号和列号参数,并返回一个QModelIndex对象,用于标识模型中特定位置的数据。QModelIndex包含了与数据项相关的信息,例如父索引、有效性检查等。

  在QFileSystemModel中,每个文件和文件夹都用一个唯一的索引标识。根索引通常是模型的顶层索引,表示整个文件系统的根目录。您可以通过调用model.index(row, column, parentIndex)方法来获取特定行和列处的索引,在这里,row和column分别表示行号和列号,parentIndex表示父索引。

  在示例代码中,我们首先使用model.index(rootPath)获取了根目录的索引,然后通过model.index(i, 0, rootIndex)获取了子文件和子文件夹的索引。这些索引可以用于获取对应数据项的信息,如文件名、大小等。

posted on 2024-06-21 19:09  一杯清酒邀明月  阅读(31)  评论(0编辑  收藏  举报