View Full Version : QListView and QStringListModel

6th December 2019, 02:03
Good evening,
I am developing an application where I have to process a bunch of image files.
To load the file's list, the user have to press a load button and a QFileDialog is created, then I populate a QStringList model with the file's paths.
To show the list I use a QListView

Here the code:

QFileDialog fileDialog;
fileDialog.setWindowTitle(tr("Open Directory"));
fileDialog.setFileMode(QFileDialog::DirectoryOnly) ;

if (fileDialog.exec() == QDialog::Accepted)
QStringList files = getImageFiles(fileDialog.selectedFiles().first());

// Populate the model

// and pass it to the view

QStringList MainWindow::getImageFiles(const QString& path) const
QStringList result;
QDir root(path);

QStringList dirs = root.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name);

foreach (const QString& dir, dirs)

QStringList files = root.entryList(QString("*.jpg").split(";"), QDir::Files, QDir::Name);

foreach (const QString& file, files)

return result;

Now in the view I have a list of full paths, but I would only show the files names instead of full path while keeping the full paths in the model
How can I do it? I would have an help on it.
Thanx in advance

6th December 2019, 18:33
How can I do it? I would have an help on it.

Derive a custom model from QStringListModel, and override the data() method. In the handler for DisplayRole, use QFileInfo to retrieve the file name only from the path (using QFileInfo::fileName()) and return that as the QVariant. For all other data roles, call the QStringListModel base class data() method.

For your processing where you need the entire path, you can implement a handler for Qt::UserRole in your custom model. For that role, you call the base class data() method with the Qt::DisplayRole role, which will return the entire path string. In your list-handling code, you would call into the model with the UserRole when you need the full path.