How to flatten a TreeView to show only the leaf node items?
-
I want to add a checkbox toggle to my application where a tree view gets flattened to show only the leafs nodes (child items with no children). When the toggle is unselected it should go back to the original treeview.
Something like this:
A -B -C -D -E -F -G -H -I -K
Should become
-C -E -F -K
I tried setting the treeView indentation to 0 when the QCheckbox is toggled and the setting indentation back to 20 when unchecked.
This sort of gives the desired results but still shows the parent nodes.
I have a class overriding QSortFilterProxyModel that is used to filter the elements in the QTreeview based on a search text. I tried to play around with it to hide the parents and cannot seem to figure it how to do it.
SearchFilter.h: QSortFilterProxyModel
bool FileFilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { QModelIndex index0 = sourceModel()->index(source_row, 0, source_parent); QModelIndex index1 = sourceModel()->index(source_row, 1, source_parent); if (!index0.isValid()) return false; if (sourceModel()->data(index0).toString().contains(this->filterRegularExpression()) || sourceModel()->data(index1).toString().contains(this->filterRegularExpression())) return true; int rows = sourceModel()->rowCount(index0); for (int row = 0; row < rows; row++) { if (filterAcceptsRow(row, index0)) return true; } return false; }
-
I had a similar question, see https://forum.qt.io/topic/71553/smarter-way-to-get-a-list-of-children-in-tree-model
The 3-proxy-models solution works (you'll just need to changeLevelDataProxy::data
to match your use case and I'm still using it in my project without performance taking a big hit (even if the model gets quite big) -
@ralphtink said in How to flatten a TreeView to show only the leaf node items?:
I don't want to import a whole library just for this
I would strongly suggest you do but even if you want to go against my advice you can just:
- take kbihash_p.h, kdescendantsproxymodel.h and kdescendantsproxymodel.cpp
- add the files to your project
- replace
#include "kitemmodels_export.h"
with#define KITEMMODELS_EXPORT
- satisfy LGPL 2 requirement on the imported code