Converting QModelIndex to QString
Asked Answered
A

3

6

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!

Anaplastic answered 15/5, 2012 at 9:45 Comment(0)
C
5
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.

Cilium answered 15/5, 2012 at 10:3 Comment(0)
E
3

No, is the short answer. A QModelIndex is an index into a model - not the data held in the model at that index. You need to call data( const QModelIndex& index, int role = Qt::DisplayRole) const on your model with index being your QModelIndex. If you're just dealing with text the DislayRole should sufficient.

Yes the way you are getting the selected item is correct, but depending your selection mode, it may return more than one QModelIndex (in a QModelIndexList).

Eyewash answered 15/5, 2012 at 10:2 Comment(0)
L
1

QModelIndex is identifier of some data structure. You should read QModelIndex documentation. There is a QVariant data(int role) method. In most cases you will need Qt::DisplayRole to get selected item text. Note that also selectIndexes() returns a list of QModelIndex. It may be empty or contain more then one item. If you want to get (i.e. comma separated) texts of all selected indexes you should do something like this:

QModelIndexList selectedIndexes = foolistView->selectionModel()->selectedIndexes();
QStringList selectedTexts;

foreach(const QModelIndex &idx, selectedIndexes)
{
    selectedTexts << idx.data(Qt::DisplayRole).toString();
}

bar.setText(selectedTexts.join(", "));
Leffen answered 15/5, 2012 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.