QTreeView: Filtering contents - looking for best practices
I have a QTreeView in which I wish to filter the contents. I only wish to filter these contents on the top level children (the ones immediately below the root index). Currently I am accomplishing this by creating a simple filtering method in my QTreeView subclass and selectively hiding those rows that do not match.
While the above approach seems to work fine, I am wondering whether I should re-implement this using a QSortFilterProxyModel. If so, what would be the advantages?
If I change to using the QSortFilterProxyModel, I have a few (hopefully small) questions:
1) Since I am filtering only on the top-level children, I would have to re-implement whatever method was actually doing the sorting so that it would leave all the grandchildren alone, right?
2) My data model has a number of custom methods in it that are responsible for unique keyboard navigation and the like. Do I re-implement these in the proxy model and have them po开发者_运维百科int to my data model's methods? If so, how to I reference the model? I can't seem to find any thing comparable to a QTreeView's model() method.
Thanks!
Using a derived class from QSortFilterProxyModel is better. You keep responsibilities of sorting outside of your tree view.
To reuse at maximum the existing code, you can override filterAcceptsRow like this
bool MySortFilterProxyModel::filterAcceptsRow(int sourceRow,
const QModelIndex &sourceParent) const
{
if( sourceParent.IsValid() ) return true; // Don't filter other than top level
return QSortFilterProxyModel( sourceRow, sourceParent );
}
For the custom methods, you will need to implement them in your proxy. Then for the navigation, you may need to used mapToSource and mapFromSource to convert proxy index to orignal model index
精彩评论