Qt 如何从QListView中的选定项获取QString?

Qt 如何从QListView中的选定项获取QString?,qt,qstring,qlistview,Qt,Qstring,Qlistview,我需要在QListView中以QString的形式获取所选项目名称。我试过用谷歌搜索,但没有发现任何有用的东西。这取决于选择模式,比如说你有ExtendedSelection,这意味着你可以选择任意数量的项目(包括0) ui->listView->setSelectionMode(QAbstractItemView::ExtendedSelection); 您应该迭代通过ui->listView->selectionModel()->selectedIndexes()查找所选项目的索引,然后调

我需要在
QListView
中以
QString
的形式获取所选项目名称。我试过用谷歌搜索,但没有发现任何有用的东西。

这取决于选择模式,比如说你有
ExtendedSelection
,这意味着你可以选择任意数量的项目(包括0)

ui->listView->setSelectionMode(QAbstractItemView::ExtendedSelection);
您应该迭代通过
ui->listView->selectionModel()->selectedIndexes()
查找所选项目的索引,然后调用
text()
方法获取项目文本:

QStringList list;
foreach(const QModelIndex &index, 
        ui->listView->selectionModel()->selectedIndexes())
    list.append(model->itemFromIndex(index)->text());
qDebug() << list.join(",");
QStringList列表;
foreach(常数QModelIndex和索引,
ui->listView->selectionModel()->SelectedIndex())
追加(model->itemFromIndex(index)->text());

qDebug()如果禁用了
QAbstractItemView::ExtendedSelection
(一次只能选择一个项目),则无需任何循环即可执行此操作:

QModelIndex index = ui->listView->currentIndex();
QString itemText = index.data(Qt::DisplayRole).toString();

查看
QListView
文档(尤其是its),了解如何获取当前索引(一个
QModelIndex
对象),并从索引中获取其数据内容(一个可以转换为
QString
QVariant
)。这里的“model”是什么?对于禁用了
qabstractemview::ExtendedSelection
的QListView,是否有一种干净的方法来使用它?即,如果只有一个选择是可能的,循环和列表因此变得不必要?