如何在QTreeView中隐藏孙子孙女
How to hide grandchildren in QTreeView
我使用树/表模型(继承自QStandardItemModel)和几个用于不同目的的视图。
模型的某些行具有子行,其中一些行也可能具有子行,依此类推。
在 QTreeView 中,我只想显示顶级行和他们的"一级子级" - 孙子和他们的孩子应该被隐藏。
我该怎么做?
您需要使用 QSortFilterProxyModel。
看例子
bool YourQSortFilterProxyModel::filterAcceptsRow ( int source_row, const QModelIndex & source_parent ) const
{
if (source_parent == qobject_cast<QStandardItemModel*>(sourceModel())->invisibleRootItem()->index())
{
// always accept children of rootitem, since we want to filter their children
return true;
}
return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
}
我的工作解决方案,基于弗拉迪斯拉夫·米基蒂奇的回复:
bool ArchiveQSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
if (source_parent == qobject_cast<QStandardItemModel*>(sourceModel())->invisibleRootItem()->index())
{
// always accept children of rootitem, since we want to filter their children
return true;
}
if (source_parent.parent() == qobject_cast<QStandardItemModel*>(sourceModel())->invisibleRootItem()->index())
{
return true;
}
if (source_parent.parent().parent() == qobject_cast<QStandardItemModel*>(sourceModel())->invisibleRootItem()->index())
{
return false;
}
return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
}