How to select a row in a QListView
Asked Answered
A

3

17

I'm still struggling with using QListView, I'm trying to select one particular row in the view and I cannot figure out how to do this.

I found a similar question on StackOverflow which recommends using the createIndex() method of the model, however this method is protected (perhaps it used to be public but is not anymore) so that doesn't work for me. Any suggestion?

Abandon answered 3/8, 2011 at 11:48 Comment(0)
F
27

You can get the index of anything by just calling

QModelIndex indexOfTheCellIWant = model->index(row, column, parentIndex);

Then you can call setCurrentIndex(indexOfTheCellIWant) as bruno said in his answer.

If model contains just a standard list of items as opposed to a tree structure, then it's even easier. Because we can assume that the item is a root item - no parent.

QModelIndex indexOfTheCellIWant = model->index(row, column);

With a tree structure it is a little trickier, because we can't just specify a row and a column, we need to specify these with respect to a parent. If you need to know about this part let me know and I'll explain more.

Only one more thing to note. Selection is based on cells, not really rows. So if you want to ensure that when the user selects a cell (or you do through code) that the whole row is selected you can do that by setting the "selectionBehavior" on the itself.

list->setSelectionBehavior(QAbstractItemView::SelectRows);
Filature answered 3/8, 2011 at 18:42 Comment(1)
This still doesn't answer e.g. how to select row #4. The problem is stated "trying to select one particular row" - you mention "parentIndex" but you leave it without explanation - this makes you answer NON-SENSE.Contortionist
T
3

You can use QAbstractItemView::setCurrentIndex ( const QModelIndex & index )

Toh answered 3/8, 2011 at 12:11 Comment(1)
Thanks, I didn't know about this method. It's still not clear how I should select a row though. On the doc, it's written to use createIndex() but since it's a protected method, I cannot use it. The constructor of QModelIndex doesn't let me specify a row either. Is there any other way?Abandon
C
0

Fetch an instance of QModelIndex from the QListView's model and select it:

void selectRowInQListView(int row, QListView *listView) {
    QModelIndex index = listView->model()->index(row, 0);
    if (index.isValid()) {
        //listView->selectionModel()->select(index, QItemSelectionModel::Select);
        //listView->selectionModel()->select(index, QItemSelectionModel::Current);
        listView->setCurrentIndex(index);
    }
}
Contortionist answered 25/9, 2022 at 9:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.