How to get QString from QListView selected item in Qt?
30,242
Solution 1
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(",");
Solution 2
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();
Author by
MartinS
Updated on April 13, 2020Comments
-
MartinS about 4 years
I need to get the selected item name in
QListView
as aQString
. I have tried to google, but I haven't found anything useful. -
Praneeth Peiris almost 10 yearsWhat is `model' here?
-
Paddre almost 9 yearsIs 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?