I have a QLineEdit
and a QListView
. I use QStringListModel
to populate the QListView
with items.
If I type something in the QLineEdit
, how can I find and select an item from the QListView
that begins with the text that I am typing in the QLineEdit
?
The general approach is:
textChanged
of the line edit to a slot of your choice.model
on the list view)QAbstractItemModel
which has a match
function for search (documentation)match
with Qt::MatchStartsWith
as match flag and the appropriate role (display role) and you get a list of model indicesselectionModel
) and call select
with each index in the list of indices resulting from the call to match
(some may already be selected)To give some more practical advice.
Example call to match:
model->match(model->index(0, 0), Qt::DisplayRole, QVariant::fromValue(search_text), -1, Qt::MatchStartsWith);
This searches from the start to the end, taking the displayed text of the list view and compares it with a search text and returns all found matches where the displayed text starts with the search text.
Example call to select:
model->selectionModel()->select(index, QItemSelectionModel::Select);
Which will select the index (with different flags you can unselect or toggle the selection).
Example for iterating over the QModelIndexList
which is a shortcut for QList<QModelIndex>
:
foreach(QModelIndex modelIndex, modelIndexList)
selectionModel->select(modelIndex, QItemSelectionModel::Select);