Convert QModelIndex to QString

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

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 right way to get the currently selected item?

Thanks in advance!

+4
source share
3 answers
 foolistView->selectionModel()->selectedIndexes(); 

Sends you a QList from QModelIndex (only one if you look in QAbstractItemView :: SingleSelection)

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

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

+4
source

No, this is a short answer. A QModelIndex is the index into the model, not the data stored in the model at that index. You should 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, a DislayRole should suffice.

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

+3
source

QModelIndex is an identifier for some data structure. You should read the QModelIndex documentation. There is a QVariant data(int role) method. In most cases, you will need Qt :: DisplayRole to get the selected text of the element. Note that selectIndexes () returns a list of QModelIndex. It can be empty or contain more than one element. If you want to get (i.e. separated by commas) the texts of all the 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(", ")); 
+1
source

Source: https://habr.com/ru/post/1412535/


All Articles