前言:
QT提供了调用文件系统的方法,非必要情况下不要自己去写,直接用就好。
QFileSystemModel
The QFileSystemModel class provides a data model for the local filesystem.
This class provides access to the local filesystem, providing functions for renaming
and removing files and directories, and for creating new directories. In the simplest
case, it can be used with a suitable display widget as part of a browser or filter.QFileSystemModel can be accessed using the standard interface provided by
QAbstractItemModel, but it also provides some convenience functions that
are specific to a directory model. The fileInfo(), isDir(), fileName() and filePath()
functions provide information about the underlying files and directories related to items
in the model. Directories can be created and removed using mkdir(), rmdir().
QFileSystemModel
调用方法:
QFileSystemModel *model = new QFileSystemModel;
model->setReadOnly(false); //设置可以修改
model->setRootPath("/");
QTreeView *treeView = new QTreeView;
treeView->setModel(model);
//treeView非必要设置
//treeView->setFont(tree_font);
//treeView->header()->setStretchLastSection(true); //adapt //width
//treeView->header()->setSortIndicator(0, Qt::AscendingOrder);
//treeView->header()->setSortIndicatorShown(true);
//treeView->header()->setSectionsClickable(true);
treeView->setRootIndex(model->index('特定目录'))//直接显示特定目录
//定位特定目录,并从根目录进行展开显示
//QModelIndex index = model->index(QDir::currentPath());
//QModelIndex index = model->index("特定目录");
//qDebug()<<model->fileName(index);
//treeView->expand(index); //当前项展开
//treeView->scrollTo(index); //定位到当前项
//treeView->resizeColumnToContents(0);
关于刷新目录,可以在按钮的槽函数中按如下方式写
void refresh()
{
model = new QFileSystemModel;
model->setReadOnly(false); //设置可以修改
model->setRootPath("/");
treeView->clearSelection(); //清除缓存
treeView->setModel(model);
treeView->setRootIndex(model->index('特定目录'));
}
说明:关于刷新的注意事项
1、QFileSystemModel实际上默认刷新,但是对于挂载设备,它是不刷新的,必须要手动;
2、model要重新申请;
3、treeView不能重新申请,只能重新setModel()
,否则起不到刷新效果;
4、在treeView重新设置之前,需要clear一下,原因在于,用户在QTreeView控件里进行点击或其他操作后,有些信息会被控件自动存储,不清除这些信息便直接setModel,会导致程序意外崩溃。