Search code examples
c++qtqt4

How to get the text of selected item from QListView in QT?


I need to get the selected item name in QListView as a QString. I have tried to google, but I have not found anything useful.

My QListView, Model and the method to populate it is as follow:

QString setting_path = QDesktopServices::storageLocation(QDesktopServices::DataLocation);

QStandardItemModel *model2=new QStandardItemModel();

QFile file(setting_path+"history.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    return;

QTextStream in(&file);

while(!in.atEnd()) {
QString line = in.readLine();
QList<QStandardItem *> items;
QStringList fields = line.split(">");
QStringList fields3 = fields.filter("");

foreach (QString text, fields3)
{
    items.append(new QStandardItem((QString)text));
}

if(items.length() > 0)
{
    model2->appendRow(items);
}
}
 ui->listView->setModel(model2);
}

Solution

  • Solved with the following code :

    void hist::on_listView_clicked(const QModelIndex &index)
    {
        QModelIndexList templatelist = ui->listView
                                         ->selectionModel()
                                         ->selectedIndexes();
        QStringList stringlist;
        foreach (const QModelIndex &index, templatelist){
            stringlist.append(index.data(Qt::DisplayRole).toString());
        }
        qDebug() << stringlist.join(",");
    }
    

    enter image description here

    Thanks everybody !