I want to create a search field that filters the items shown in a QListView. Basically the user could type in "foo" and only items with "foo" in the DisplayRole are shown.
I already have a few ideas on how to do this, but thought I'd ask those more experienced than I.
My idea would be to use some signals and slots to set a filter in the QAbstractItem model and trigger an update() in the QListView.
Are there any helper methods in QListView for filtering I may have missed?
Is there a canonical way of handling this I haven't run across?
edit
Current progress.
I created a public slot called "updateFilter(QString)" in my QFileSystemModel subclass. Then I
connect(myQLineEditSearch, SIGNAL(textChanged(QString)),
myQFileSysModel, SLOT(updateFilter(QString)));
This sets the filter, then in my QFileSystemModel::data(...) method, I have:
void ComponentModel::updateFilter(QString filter)
{
_filter = filter;
emit layoutChanged();
}
QVariant ComponentModel::data(const QModelIndex &index, int role) const
{
QVariant result;
// if our search filter term is set and the item does not match,
// do not display item data. Searches are case insensitive
if (!_filter.isEmpty() &&
!QFileSystemModel::data(index, Qt::DisplayRole)
.toString().toLower().contains(_filter.toLower()))
{
return result;
}
result = QFileSystemModel::data(index, role);
return result;
}
This is almost there. The "glitch" I'm working on has to do with where the object is displayed. Currently, if I apply a search that matches the 3rd item in the list only the first two rows are rendered as blank. In other words, it still renders the rows for non-matched items.