目标
- QTableView+QFileSystemModel显示指定目录下的文件
- QTableView能够动态显示目录下文件的变化情况(文件的删除和新增)
- 第一列显示序号、第二列显示文件名称、第三列显示文件大小
效果图
- 效果图显示可执行程序目录下的
exe 文件

完整代码
#include <QApplication>
#include <QTableView>
#include <QFileSystemModel>
#include <QHeaderView>
#include <QDir>
#include <QVBoxLayout>
#include <QWidget>
class FileSystemModel : public QFileSystemModel
{
Q_OBJECT
public:
explicit FileSystemModel(QObject* parent = nullptr) : QFileSystemModel(parent) {}
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override
{
if (role == Qt::DisplayRole)
{
if (index.column() == 0)
{
// 第一列显示文件序号
return index.row() + 1;
}
else if (index.column() == 1)
{
// 第二列显示文件名称
return QFileSystemModel::data(this->index(index.row(), 0, index.parent()), role);
}
else if (index.column() == 2)
{
// 第三列显示文件大小
return QFileSystemModel::data(this->index(index.row(), 1, index.parent()), role);
}
}
return QFileSystemModel::data(index, role);
}
int columnCount(const QModelIndex& parent = QModelIndex()) const override
{
// 返回3列:序号、名称、大小
return 3;
}
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
if (section == 0)
{
return "Index";
}
else if (section == 1)
{
return "Name";
}
else if (section == 2)
{
return "Size";
}
}
return QFileSystemModel::headerData(section, orientation, role);
}
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QWidget window;
window.resize(1000, 800);
QVBoxLayout* layout = new QVBoxLayout(&window);
QTableView* tableView = new QTableView;
FileSystemModel* model = new FileSystemModel;
// 启用文件监控
model->setOption(QFileSystemModel::DontWatchForChanges, false);
model->setNameFilterDisables(false);
model->setFilter(QDir::Dirs | QDir::Drives | QDir::Files | QDir::NoDotAndDotDot);
QStringList list_name;
list_name << "*.exe";
model->setNameFilters(list_name);
const QString strTmp = QApplication::applicationDirPath();
// 设置根目录
model->setRootPath(strTmp);
// 设置模型
tableView->setModel(model);
// 设置根索引
tableView->setRootIndex(model->index(strTmp));
// 设置列宽
tableView->setColumnWidth(0, 100); // 序号列
tableView->setColumnWidth(1, 300); // 名称列
tableView->setColumnWidth(2, 100); // 大小列
tableView->verticalHeader()->setVisible(false);
// 隐藏不需要的列
tableView->hideColumn(3); // 隐藏文件类型列
tableView->hideColumn(4); // 隐藏修改日期列
layout->addWidget(tableView);
window.setLayout(layout);
window.show();
return app.exec();
}