Search code examples
qtqlistviewqstandarditemmodel

QListView with QStandardItemModel does not show selection highlight through code


I have a QListView that is populated with either a QStandardItemModel or a QStringListModel (based on simplicity of contents... number of columns).

On load, or switching between widgets, I search for the item that should be selected, and try to highlight it.

if (first)
{
    m_myListView.setModel(m_standardItemModel);

    QList<QStandardItem*> lst = m_standardItemModel->findItems(m_value1, Qt::MatchExactly, 1);
    if(!lst.isEmpty())
    {
        QModelIndex index = lst.at(0)->index();
        qDebug() << index.row();                  // tells me correct row
        //m_myListView.setCurrentIndex(index);    // no change if I use
        m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
        m_myListView.scrollTo(index);
    }
}
else
{
    m_myListView.setModel(m_stringListModel);

    int i = m_stringListModel->stringList().indexOf(m_value2);
    if (i >= 0)
    {
        QModelIndex index = m_stringListModel->index(i);
        m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
        m_myListView.scrollTo(index);
    }
}

The m_stringListModel version correctly highlights (and scrolls to item).
The m_standardItemModel version does not highlight row, and does not scroll to item. But in the uses afterwards, it correctly provides the data for selected index:

QModelIndexList indexList = m_myListView.selectionModel()->selectedIndexes();
if (!indexList.isEmpty())
{
    QModelIndex index = indexList.first();
    if (index.isValid())
    {
        row = index.row();
        data1 = m_standardItemModel->index(row, 1).data().toString();

...

So... it seems that the selection works, but if it does, why do I not see a highlight ? (and the scrollTo() )

Note - the code is pretty giant but I verified for the possibility of reloading the model and possibly losing the selection - and besides, the QStringListModel version works correctly.

Is that a typical behavior of QStandardItemModel, or is there something I must do, like setting a BackgroundRole type data ?

How can I highlight the selection of the list view with the QStandardItemModel applied ?


Solution

  • Because the item found is different than the display item, the list view is unable to select it...

    2 solutions: either create a different QModelIndex from the one found, pointing to the display column, or select an entire row containing the desired index:

    m_myListView.selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);