I am having a QListView
which contains some items. Now I want to get the index of selected item, i.e. if I select 5th element I should get 5. How I can get this?
How to get selected listitem index in Qt
In every view in Qt, you have the following method :
QItemSelectionModel * QAbstractItemView::selectionModel () const
Basically, it returns a model on which you can perform actions, like getting selected indexes...
Have a look here : QItemSelectionModel
You'll find plenty of methods to help you get your index(es).
Hope it helps!
Andy i got it, but I found selectedIndexes (), but selected indexes will give the list, we need to iterate for getting the modelindex. But I wanted an API which gives the selected item modelindex in one shot.. iterating the list is time consuming right.. is ther any direct way, or we need to do like this only –
Resonant
Yes, you have currentIndex() that will give you the current index in your selection... I don't know if you know the difference between selected items and current index... The current index is kinda the last index you selected... So I think it will be what you're looking for... –
Latin
There can be major difference between current index and selected index. The current one is the one with focus in the list, and it may or may not be selected. At my company, we made a quick wrapper function to get the selection model, get the selection list, and if the list isn't empty, return the first item in the list. That works for lists that are set to not allow multiple selections, and you really only need to write the function once. –
Magistral
The link seems to be unavailable (at least at the moment). So for everyone facing the same problem: I got the index of the currently selected item like this:
listWidget->selectionModel()->currentIndex().row()
eventually –
Wyn There is no easy way to do this, since QListView can handle tree like structures. You can make your list items derive from QListViewItem and add an extra data member to hold an index. You have to reset the indexes when sorting of course.
© 2022 - 2025 — McMap. All rights reserved.