赞
踩
在使用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盘在模型中的索引
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。