I want to create a search field that filters the items shown in a QListView. Basically, the user can enter "foo" and only items with "foo" in the DisplayRole will be shown.
I already have a few ideas on how to do this, but I thought that I would ask those who are more experienced than me.
My idea would be to use some signals and slots to set a filter in the QAbstractItem model and run update () in a QListView.
Are there any helper methods in QListView for filtering that I might have missed?
Is there a canonical way to handle this I have not come across?
change
Current progress.
I created a public slot called "updateFilter (QString)" in my subclass of QFileSystemModel. Then I
connect(myQLineEditSearch, SIGNAL(textChanged(QString)), myQFileSysModel, SLOT(updateFilter(QString)));
This parameter 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; }
It is almost that. The "crash" I'm working on is related to where the object is displayed. Currently, if I apply a search matching the 3rd item in the list, only the first two lines are displayed as empty. In other words, it still displays strings for inconsistent items.
c ++ qt4
jkyle
source share