How to get QString from QListView selected item in Qt?

MartinS picture MartinS · Jun 28, 2012 · Viewed 27.6k times · Source

I need to get the selected item name in QListView as a QString. I have tried to google, but I haven't found anything useful.

Answer

KCiebiera picture KCiebiera · Jun 28, 2012

It depends on selectionMode lets say you have ExtendedSelection which means you can select any number of items (including 0).

ui->listView->setSelectionMode(QAbstractItemView::ExtendedSelection);

you should iterate through ui->listView->selectionModel()->selectedIndexes() to find indexes of selected items, and then call text() method to get item texts:

QStringList list;
foreach(const QModelIndex &index, 
        ui->listView->selectionModel()->selectedIndexes())
    list.append(model->itemFromIndex(index)->text());
qDebug() << list.join(",");