开发者

How to select a row in a QListView

开发者 https://www.devze.com 2023-03-25 03:28 出处:网络
I\'m still struggling with using QListView, I\'m trying to 开发者_JAVA技巧select one particular row in the view and I cannot figure out how to do this.

I'm still struggling with using QListView, I'm trying to 开发者_JAVA技巧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?


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);


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


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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号