QListWidget selectedItem indexes
-
I am making a program and in it I have a QListWidget that will gain QListWidgetItems over time, after selecting one or many I need to know their INDEX in the list so after I have the list item I can do further computation later based off of its INDEX in the list.
Essentially, is there a way to get the indexes of all selected QListWidgetItems? I have been researching it and so far I have not found much.
I did find one example where they used the selection model, but it is not returning numerical indexes like 0, 1, 2, 3 etc.
myQList->selectionModel()->selectedIndexes();
I have also found that you can also use the following algorithm to store the selected items' indexes:
QList<int> myVector; QList<QListWidgetItem*> selectedI{m_Ui->myQListWidget->selectedItems()}; for(auto listItem: selectedI) myVector.append(selectedI.indexOf(listItem));
This last method has served me quite well, however IF I have read the documentation right,
indexOf()
, finds the index by SEARCHING rather than knowing, essentially if I have 10000 QListWidgetItem's and I have to search for all the selected items I feel like there is a lot more work going on than it needs to. This method does work, but in my opinion is expensive, is there some sort of function that can be called that already has these indexes so I don't need to be searching for them? -
@cdecde57 In that case, it is not necessary to use
indexOf()
since this will return the indexes with respect to the list of the selected elements and not with respect to all the QListWidgetItems.In this case there are 2 solutions:
for(QListWidget *item: m_Ui->myQListWidget->selectedItems()){ int row = m_Ui->myQListWidget->row(item); qDebug() << row; }
OR
for(QModelIndex index: m_Ui->myQListWidget->selectedIndexes()){ int row = index.row(); qDebug() << row; }
-
@cdecde57 Your question is confusing to me: do you want the index with respect to the list of selected elements or with respect to the items in the QListWidget? For example, let's say there are 10 items with text in the format:
{"item0", "item1", "item2", ..., "item9"}
. And the items are selected:{"item2", "item4", "item5"}
, if the item is"item2"
then do you want to get2
or0
? -
@cdecde57 In that case, it is not necessary to use
indexOf()
since this will return the indexes with respect to the list of the selected elements and not with respect to all the QListWidgetItems.In this case there are 2 solutions:
for(QListWidget *item: m_Ui->myQListWidget->selectedItems()){ int row = m_Ui->myQListWidget->row(item); qDebug() << row; }
OR
for(QModelIndex index: m_Ui->myQListWidget->selectedIndexes()){ int row = index.row(); qDebug() << row; }