Converting QModelIndex to QString

NHI7864 picture NHI7864 · May 15, 2012 · Viewed 9.7k times · Source

Is there a way to convert QModelIndex to QString? The main goal behind this is that I want to work with the contents of dynamically generated QListView-Items.

QFileSystemModel *foolist = new QFileSystemModel;
    foolist->setRootPath(QDir::rootPath());
    foolistView->setModel(foolist);

[...]

QMessageBox bar;
QString foolist_selectedtext = foolistView->selectionModel()->selectedIndexes();
bar.setText(foolist_selectedtext);
bar.exec;

Is this even the correct way to get the currently selected Item?

Thanks in advance!

Answer

Jokahero picture Jokahero · May 15, 2012
foolistView->selectionModel()->selectedIndexes();

Send you back a QList of QModelIndex (only one if you view is in QAbstractItemView::SingleSelection)

The data method of QModelIndex return a QVariant corresponding to the value of this index.

You can get the string value of this QVariant by calling toString on it.