QFileSystemModel类显示根目录不起作用及setRootPath、setRootIndex函数的区别

问题描述

       在使用QTreeView制作本地文件浏览功能的时候,发现QFileSystemModel调用setRootPath()函数设置树显示的根目录不起作用。即使用后,QTreeView并不显示setRootPath()函数设置的目录和文件,而是显示主机根目录下的全部文件。
代码片段如下:

    m_model = new QFileSystemModel(this);
    m_model->setRootPath(R"(D:\)"); // 原意是想将 D:\ 目录下的所有子目录和文件显示到树

    m_treeview = new QTreeView(this);
    m_treeview->setModel(m_model);

上述代码的原意是:将 D:\  目录下的所有子目录和文件显示到树,即如下那样的结果:

 图1:显示D盘下的文件系统 

 但结果却是将Windows下我的电脑下所有盘符都显示出来,且D盘在树的第一项显示,如下:

                                                    图2:显示“我的电脑”下的文件系统 

 造成这种情况的原因是对setRootPath、setRootIndex函数没能深刻理解、望文生义造成的。Qt官方对setRootPath的解释如下:

QModelIndex QFileSystemModel::setRootPath(const QString &newPath)

Sets the directory that is being watched by the model to newPath by installing a file system watcher on it. Any changes to files and directories within this directory will be reflected in the model.

If the path is changed, the rootPathChanged() signal will be emitted.

Note: This function does not change the structure of the model or modify the data available to views. In other words, the "root" of the model is not changed to include only files and directories within the directory specified by newPath in the file system.

翻译过来就是:

       setRootPath函数设置QFileSystemModel类内部的QFileSystemWatcher类监控的目录。每个QFileSystemModel类对象内部都有一个QFileSystemWatcher类对象,QFileSystemWatcher类对象对setRootPath函数设置的目录进行监控,当该目录中的子目录、文件被删除、重命名或者有新目录或文件加入到目录时,即该目录有任何改变时,QFileSystemWatcher类对象就会告知QFileSystemModel类,从而导致QFileSystemModel类做出相应的改变。如果通过setRootPath函数设置了一个和以前设置的不同目录,则会发送 rootPathChanged信号。

         注意:setRootPath函数不会修改模型结构和显示在视图上的可利用数据。换句话来说:该函数不会改变模型的根结构,不会使根结构仅仅包含该函数参数指定的目录内的子目录或文件。

要实现图1中显示D盘下的文件系统,必须用QTreeView类的setRootIndex函数,代码如下:

    m_model = new QFileSystemModel(this);
    m_treeview = new QTreeView(this);
    m_treeview->setModel(m_model);
    auto rootModelIndex = m_model->index(R"(D:\)"); // 获取d盘在模型中的索引
    m_treeview->setRootIndex(rootModelIndex); // 设置树视图的根索引为d盘在模型中的索引

  • 11
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值