How to get QString from QListView selected item in Qt?

前端 未结 2 735
你的背包
你的背包 2020-12-05 19:07

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.

相关标签:
2条回答
  • 2020-12-05 19:41

    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();
    
    0 讨论(0)
  • 2020-12-05 19:52

    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(",");
    
    0 讨论(0)
提交回复
热议问题