-1

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);
}
bulldog68
  • 197
  • 1
  • 10

2 Answers2

3

I think, you may use selectedIndexes() for this

QModelIndexList QListView::selectedIndexes() const;

So, when you need to take the items - just call this method and get items from your model (by your accessors, or by using data(index) with your/system role, or by any way you have to get the items by index which is row and column.

For example, this is how to get the first item:

void MyListView::somethingIsSelected() {
    const auto selectedIdxs = selectedIndexes();
    if (!selectedIdxs.isEmpty()) {
        const QVariant var = model()->data(selectedIdxs.first());
        // next you need to convert your `var` from `QVariant` to something that you show from your data with default (`Qt::DisplayRole`) role, usually it is a `QString`:
        const QString selectedItemString = var.toString();

        // or you also may do this by using `QStandardItemModel::itemFromIndex()` method:
        const QStandardItem* selectedItem = dynamic_cast<QStandardItemModel*>(model())->itemFromIndex(selectedIdxs.first());
        // use your `QStandardItem`
    }
}
VP.
  • 15,509
  • 17
  • 91
  • 161
0

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 !

Alex44
  • 3,597
  • 7
  • 39
  • 56
bulldog68
  • 197
  • 1
  • 10