How to select a row in a QListView

I'm still trying to use QListView, I'm trying to select one specific row in a view, and I cannot figure out how to do this.

I found a similar question in StackOverflow that recommends using the createIndex() method of the model, however this method is protected (it may have been publicly available, but it is no more), so this does not work for me. Any suggestion?

+6
source share
2 answers

You can get the index of everything just by calling

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

You can then call setCurrentIndex(indexOfTheCellIWant) , as Bruno said in his answer.

If the model contains only a standard list of elements, and not a tree structure, then this is even easier. Because we can assume that the element is the root element - without a parent.

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

With a tree structure, this is a little more complicated because we cannot just specify the row and column, we need to specify them relative to the parent. If you need to know about this part, let me know and I will explain more.

One more remark. The selection is based on cells, not rows. Therefore, if you want to make sure that when the user selects a cell (or you do it through the code) that the entire row is selected, you can do this by setting "selectionBehavior" to yourself.

 list->setSelectionBehavior(QAbstractItemView::SelectRows); 
+15
source

Source: https://habr.com/ru/post/894183/


All Articles