QListView and QStringListModel
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:
Code:
fileDialog.setWindowTitle(tr("Open Directory"));
if (fileDialog.
exec() == QDialog::Accepted) {
QStringList files
= getImageFiles
(fileDialog.
selectedFiles().
first());
// Populate the model
m_model->setStringList(files);
// and pass it to the view
ui->listView->setModel(m_model);
}
QStringList MainWindow
::getImageFiles(const QString
& path
) const {
foreach (const QString& dir, dirs)
{
result.append(getImageFiles(root.filePath(dir)));
}
foreach (const QString& file, files)
{
result.append(root.filePath(file));
}
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
Re: QListView and QStringListModel
Quote:
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.