C++ 获取QTreeView的根索引并返回一级
我使用C++ 获取QTreeView的根索引并返回一级,c++,qt,C++,Qt,我使用QTreeView和QFileSystemModel制作了一个非常简单的文件浏览器。现在,QTreeView可能会与它的级联结构混淆: 这是一个将所选目录设置为临时根位置的选项: 在代码中,此方法将根据给定路径将根节点设置为QTreeView。此时,我不知道如何检查无效路径: void FileView::setRootPath( const QString&str ) { // This didn't work //model->setRootPath(
QTreeView
和QFileSystemModel
制作了一个非常简单的文件浏览器。现在,QTreeView
可能会与它的级联结构混淆:
这是一个将所选目录设置为临时根位置的选项:
在代码中,此方法将根据给定路径将根节点设置为QTreeView
。此时,我不知道如何检查无效路径:
void FileView::setRootPath( const QString&str )
{
// This didn't work
//model->setRootPath(str);
//This works
ui.treeView->setRootIndex(model->index(str));
}
但我也希望能够恢复此操作并返回目录树。我想我需要的是在下面的注释行中获取一些代码:
void FileView::rootUpOneLevel() {
QString rootPath;
// Get the current root index path into the QString
...
// Set the path as new root index, provided it's not out of the original root
setRootPath(rootPath);
}
我认为,如果您想重置视图并显示整个目录树,只需执行以下操作:
ui.treeView->setRootIndex(QModelIndex());
i、 e.通过提供无效的模型索引,即根模型索引
更新
为了提升一级,您需要调用相同的setRootIndex()
函数,但将父模型索引作为参数:
void FileView::up(const QString &str)
{
QModelIndex idx = model->index(str);
ui.treeView->setRootIndex(idx.parent());
}
或
所以首先,我想我可以使用路径来完成,这很有效——除了在windows上,它不会让你再次列出驱动器。这是因为没有
D:\
的父目录。但除此之外,这是可行的:
void FileView::parentDirectory() {
QString path = model->fileInfo(ui.treeView->rootIndex()).absoluteDir().absolutePath();
setRootPath(path);
}
但是有一个更好的解决方案,它直接使用索引,避免了一些字符串操作:
void FileView::rootUpOneLevel() {
ui.treeView->setRootIndex(ui.treeView->rootIndex().parent());
}
如果rootIndex().parent()
无效-setRootIndex
已经执行了无效的检查,那么这将不会起任何作用。这是正确的解决方案
此外,虽然已为您检查有效性,并且您可以根据需要多次调用和应用.parent()
,而不会出现实际错误,但这是检查是否存在更多父目录的正确方法:
void FileView::rootUpOneLevel() {
//First go up
ui.treeView->setRootIndex(ui.treeView->rootIndex().parent());
//Now if root node isn't valid that means there's no actual root node we could see and display
emit parentAvailable(ui.treeView->rootIndex().isValid());
}
哦,是的,这很有效。现在,仅仅提升一个级别会有多困难?因此,要真正实现获取当前显示的根级别的请求,并对其执行简单的
/..
操作?这仍然不能真正执行相对向上-您首先需要检查当前路径并将其传递给向上
。但是它可能对其他人有用。model
是QFileSystemModel的一个实例,它没有方法rootIndex
。
void FileView::rootUpOneLevel() {
//First go up
ui.treeView->setRootIndex(ui.treeView->rootIndex().parent());
//Now if root node isn't valid that means there's no actual root node we could see and display
emit parentAvailable(ui.treeView->rootIndex().isValid());
}