How to get QString from QListView selected item in Qt?

僤鯓⒐⒋嵵緔 提交于 2019-11-28 23:24:55

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(",");

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!