扩展QFileSystemModel:添加新列与重命名列的实现方法
扩展QFileSystemModel添加列并重命名列的实现方案
要给QFileSystemModel新增列(比如创建日期)同时修改原有列的名称,直接修改QFileSystemModel本身并不现实,它是Qt封装好的文件系统模型。推荐使用QIdentityProxyModel做一层包装,这种方式不会破坏原模型的功能(比如文件重命名、实时刷新),还能灵活扩展列和自定义表头。
实现步骤
1. 自定义代理模型
继承QIdentityProxyModel,重写以下几个关键方法:
columnCount():返回扩展后的总列数headerData():自定义所有列的表头名称data():为新增列提供数据(比如文件创建日期)
#include <QIdentityProxyModel> #include <QFileInfo> #include <QDateTime> class FileSystemProxyModel : public QIdentityProxyModel { Q_OBJECT public: explicit FileSystemProxyModel(QObject *parent = nullptr) : QIdentityProxyModel(parent) {} // 扩展列数:原4列 + 1列创建日期 int columnCount(const QModelIndex &parent = QModelIndex()) const override { return sourceModel()->columnCount(parent) + 1; } // 自定义表头名称 QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch (section) { case 0: return QString("文件名"); // 重命名原"Name"列 case 1: return QString("文件大小"); // 重命名原"Size"列 case 2: return QString("文件类型"); // 重命名原"Type"列 case 3: return QString("修改时间"); // 重命名原"Date Modified"列 case 4: return QString("创建时间"); // 新增列的名称 default: return QIdentityProxyModel::headerData(section, orientation, role); } } return QIdentityProxyModel::headerData(section, orientation, role); } // 为新增列提供数据 QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { if (role == Qt::DisplayRole && index.column() == 4) { // 获取原模型对应的索引 QModelIndex sourceIndex = mapToSource(index); QFileSystemModel *sourceModel = qobject_cast<QFileSystemModel*>(this->sourceModel()); if (!sourceModel) return QVariant(); // 获取文件信息,返回创建日期 QFileInfo fileInfo = sourceModel->fileInfo(sourceIndex); return fileInfo.birthTime().toString("yyyy-MM-dd HH:mm:ss"); } // 其他列和角色直接使用原模型的数据 return QIdentityProxyModel::data(index, role); } };
2. 在主函数中使用代理模型
把原QFileSystemModel设置为代理模型的源模型,再将代理模型绑定到QTreeView:
#include <QApplication> #include <QTreeView> #include <QFileSystemModel> int main(int argc, char *argv[]) { QApplication app(argc, argv); // 原文件系统模型 QFileSystemModel *model = new QFileSystemModel; model->setRootPath(""); model->setFilter(QDir::AllEntries); // 创建代理模型并绑定源模型 FileSystemProxyModel *proxyModel = new FileSystemProxyModel; proxyModel->setSourceModel(model); QTreeView *treeView = new QTreeView; treeView->setModel(proxyModel); // 使用代理模型 treeView->setColumnWidth(0, 250); treeView->setColumnWidth(4, 180); // 设置新增列的宽度 treeView->setWindowTitle("扩展版文件浏览器"); treeView->resize(800, 400); treeView->show(); return app.exec(); }
关键说明
- QIdentityProxyModel的优势:它是"身份代理",仅对模型数据做包装,不会改变原模型的结构和功能,原模型的文件重命名、实时刷新等特性都能正常使用。
- 创建日期兼容性:
QFileInfo::birthTime()在Windows系统下可以正确获取文件创建时间,跨平台也能兼容(Linux/macOS下对应文件的创建时间)。 - 灵活扩展:如果需要添加更多列(比如文件权限),只需要修改
columnCount()、headerData()和data()方法即可。
内容的提问来源于stack exchange,提问作者Joe J
相关产品推荐
相关产品推荐

