QT调用Linux文件系统



前言:

  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,会导致程序意外崩溃。



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值