使用QFileSystemModel同步两个视图与不同的元素
问题描述:
我正在建立一个像浏览器一样的目录树/导航窗格使用左侧的QTreeView
和右侧/主侧的图标视图使用QListView
。树方只应该显示目录(最好是非空目录......但这是一个不同的故事),而图标视图只有具有特定名称过滤器和没有目录的文件。我正在努力如何做到这一点。使用QFileSystemModel同步两个视图与不同的元素
第一:我不知道我是否应该使用一个或两个QFileSystemModels
。使用一个我必须过滤两个连接QSortFilterProxyModels
为每个视图 - 但我没有文件系统属性了......只使用正则表达式是一种限制。并且使用两种模型已经被证明是很困难的,因为我不能将QModelIndex
从一个模型映射到另一个模型,因为这些模型包含的内容不相同。例如,当我点击左侧的目录时,右侧的根路径应该更新。但目录不包含在模型中......所以这不起作用。
关于如何做到这一点的任何想法?谢谢!
答
文件目录树视图和文件导航视图如何交互?
不坚持是唯一的出路,但对我的作品:
- 一个视图模型仅过滤目录和其他文件只
- 每个视图(目录树和文件导航)使用指向某个根的单独文件模型对象
- 使用文件系统中的路径同步视图:当任一视图更改选择时(在您的情况下,t稀土元素视图)用户单击另一个是从同一个路径拿起
- 记住,有
QSortFilterProxyModel
我们首先必须从那里
void MyFileSystemWidget::startViews()
{
// First, initialize QTreeView and QTableView each with own
// QFileSystemModel/QSortFilterProxyModel(MySortFilterProxyModel)
// with individual selection e.g. QDir::Files or QDir::Dirs
//// //// ////
// Make models to point at the same root to start
const QModelIndex rootTreeViewIdx = m_pTreeSortFilterProxyModel->mapFromSource(m_pTreeDataModel->index(rootDir.path()));
m_pTreeView->setRootIndex(rootTreeViewIdx);
m_pTreeView->setCurrentIndex(rootTreeViewIdx);
const QModelIndex rootFileViewIdx = m_pListSortFilterProxyModel->mapFromSource(m_pListDataModel->index(rootDir.path()));
m_pTableView->setRootIndex(rootFileViewIdx);
// now connect tree view clicked signal
connect(m_pTreeView, SIGNAL(clicked(QModelIndex)), SLOT(onTreeViewClicked(QModelIndex)));
}
void MyFileSystemWidget::onTreeViewClicked(const QModelIndex& treeIndex)
{
// see MySortFilterProxyModel::sourceFileInfo
QString modelPath = m_pTreeSortFilterProxyModel->sourceFileInfo(treeIndex).absoluteFilePath();
if (modelPath.isEmpty())
return;
// see MySortFilterProxyModel::setSourceModelRootPath
const QModelIndex proxyIndex = m_pListSortFilterProxyModel->setSourceModelRootPath(modelPath);
m_pTableView->setRootIndex(proxyIndex);
}
QFileInfo MySortFilterProxyModel::sourceFileInfo(const QModelIndex& index)
{
if (!index.isValid())
return QFileInfo();
const QModelIndex proxyIndex = mapToSource(index);
if (!proxyIndex.isValid())
return QFileInfo();
return static_cast<QFileSystemModel*>(sourceModel())->fileInfo(proxyIndex);
}
QModelIndex MySortFilterProxyModel::setSourceModelRootPath(const QString& modelPath)
{
const QModelIndex fmIndex = static_cast<QFileSystemModel*>(sourceModel())->setRootPath(modelPath);
return mapFromSource(fmIndex);
}
获得当前视图位置