Search code examples
c++qtqlistview

How can I add each element from a QListView into a vector?


just want to put it out there that I am a beginner at C++. I'm trying get all the elements in my QListView and insert them into a Vector.

This is my loaddataset function which loads the files from a folder into the QListView:

void MainWindow::on_actionLoad_Dataset_triggered()
{
    QString sPath = QFileDialog::getExistingDirectory(this, tr("Choose catalog"), ".", QFileDialog::ReadOnly);
    QStringList filter;
    filter << QLatin1String("*.png");
    filter << QLatin1String("*.jpeg");
    filter << QLatin1String("*.jpg");
    filter << QLatin1String("*.gif");
    filter << QLatin1String("*.raw");
    filemodel -> setNameFilters(filter);

    ui -> imgList -> setRootIndex(filemodel -> setRootPath(sPath)); 
}

This is my QList function which then takes the file that the user clicks on and loads it onto a PixMap:

void MainWindow::on_imgList_clicked(const QModelIndex &index)
{
    imgNames = {};

    QString sPath = filemodel -> fileInfo(index).path();

    QString paths = filemodel -> fileInfo(index).fileName();

    //this kind of does it but instead of pushing them all it only pushes the ones that the user has clicked on instead of all
    imgNames.push_back(paths);

    map -> filename = filemodel -> filePath(index);

    map -> loadImage(scene);
    scene -> addItem(map);
}

Solution

  • You can get the list of all items from QListView like this:

        auto* m = qobject_cast<QStringListModel*>(ui->listView->model());
        const QStringList &list = m->stringList();
        QVector<QString> vec;
        std::vector<QString> vec2;
        for (const auto& l : list) {
            //using QVector
            vec.append(l);
            //or std::vector
            vec2.push_back(l);
            qDebug() << l;
        }
    

    As a side note, you can initialize your QStringList using initializer list like this:

    QStringList list = {"item1", "item2", "item3"};
    

    which will be faster and is much cleaner.