Unsolved QListView and QVector<QMap<QString, QString>> as Model
-
Is it possible to define a QVector<QMap<QString, QString>> as Model for a QListView? i know that QListView->setModel waits for an QAbstractItemModel, but is it possible?
-
you can. the how depends on what you want to achieve.
Could you make us an example of input and expected output? -
i have a QFileDialog where you can select a File and the File will be attached to the QVector<QMap>, because i want to have the filename and the file url.
QFileDialog dialog(this); dialog.setFileMode(QFileDialog::AnyFile); if (dialog.exec() == QDialog::Accepted) { mAttachments.append(QMap(dialog.selectedFiles().first(), dialog.selectedUrls().first())); }
The QListView should show me the added files. Later if you click an added File it will be opened. In the QListView it would be nice if only the filenames are shown.
-
You don't need QVector.
QMap<QString,QUrl> filesMap; int main(int argc, char *argv[]) { QApplication app(argc, argv); QListWidget* listView=new QListWidget; QFileDialog dialog; dialog.setFileMode(QFileDialog::ExistingFiles); if (dialog.exec() == QDialog::Accepted) { const QStringList& files=dialog.selectedFiles(); const QList<QUrl>& urls=dialog.selectedUrls(); for(int i=0; i<files.count(); i++) { QFileInfo info(files.at(i)); QUrl url=urls.at(i); filesMap[info.fileName()]=url; } listView->addItems(filesMap.keys()); } listView->show(); for(QString key: filesMap.keys()) qDebug()<<key<<filesMap.value(key); return app.exec(); }
The selected files are added to the QMap, the filename is the key and the url is the value.
-
@mpergand said in QListView and QVector<QMap<QString, QString>> as Model:
You don't need QVector.
Actually I think you don't need a QMap, that should be a
QVector<QPair<QString,QUrl> >
but then again, if you use a model, that should be the only place to store the data.// QStandardItemModel* model = new ... QFileDialog dialog; dialog.setFileMode(QFileDialog::ExistingFiles); model->removeRows(0,model->rowCount()); model->removeColumnss(0,model->columnCount()); if (dialog.exec() == QDialog::Accepted) { const auto files=dialog.selectedFiles(); const auto urls=dialog.selectedUrls(); Q_ASSERT(files.size()==urls.size()); model->insertColumn(0); model->insertRows(files.size()); for(int i=0;i<files.size();++i){ model->setData(model->index(i,0),files.at(i)); model->setData(model->index(i,0),urls.at(i),Qt::UserRole); } }
now you can use something like this to open the file:
QObject::connect(listView,&QAbstractItemView::doubleClicked,model,[](const QModelIndex &index)->void{ if(index.isValid()) QDesktopServices::openUrl(index.data(Qt::UserRole).toUrl()); });