Search code examples
c++qtqlineeditqlistview

How to search for and select items from a QListView?


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?


Solution

  • The general approach is:

    • Connect signal textChanged of the line edit to a slot of your choice.
    • In this slot access the model of the list view (either you have it stored or with model on the list view)
    • The model is inherited from QAbstractItemModel which has a match function for search (documentation)
    • Call the match with Qt::MatchStartsWith as match flag and the appropriate role (display role) and you get a list of model indices
    • The result can be zero, one, or more indices.
    • Get the selection model from either the list view of the model (selectionModel) 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);