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.
Asked
Active
Viewed 3.3k times
21

Aykhan Hagverdili
- 28,141
- 6
- 41
- 93

MartinS
- 751
- 3
- 12
- 27
-
3Look at the `QListView` documentation (especially its [member list](http://qt-project.org/doc/qt-4.8/qlistview-members.html) ) to see how to get the current index (a `QModelIndex` object), and from the index, you'll be able to get its data content (a `QVariant` that you can convert to a `QString`). – alexisdm Jun 28 '12 at 13:49
2 Answers
26
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(",");

KCiebiera
- 810
- 7
- 8
-
4
-
Is there a clean way to use that for QListViews with ```QAbstractItemView::ExtendedSelection``` disabled? I.e. if only one selection is possible and the loop and list therefore become needless? – Paddre Sep 04 '15 at 05:56
19
In case if QAbstractItemView::ExtendedSelection
is disabled (only possible to select one item at a time), this is how you can do it without any loop:
QModelIndex index = ui->listView->currentIndex();
QString itemText = index.data(Qt::DisplayRole).toString();

vicrucann
- 1,703
- 1
- 24
- 34