如何将QListView中的每个元素添加到向量中?

问题描述 投票:0回答:1

只是想说明一下我是C ++的初学者。我正在尝试获取QListView中的所有元素,然后将它们插入到Vector中。

这是我的loaddataset函数,它将文件从文件夹加载到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)); 
}

这是我的QList函数,它将获取用户单击的文件并将其加载到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);
}
c++ qt qlistview
1个回答
0
投票

如果您的问题是如何使用C ++ 11初始化QStringList,则可以执行以下操作:

const auto filter = QStringList{
  QLatin1String("*.png"), 
  QLatin1String("*.jpeg"), 
  QLatin1String("*.jpg"),
  QLatin1String("*.gif"),
  QLatin1String("*.raw") };
filemodel -> setNameFilters( filter );

事实上,我认为您可以删除QStringList的显式实例并将其缩短为:

filemodel -> setNameFilters( {
  QLatin1String("*.png"), 
  QLatin1String("*.jpeg"), 
  QLatin1String("*.jpg"),
  QLatin1String("*.gif"),
  QLatin1String("*.raw") } );

如果要强制翻译除明确选择退出的字符串以外的所有字符串(QLatin1String的通常使用情况,则您可能还考虑定义自己的字符串文字运算符以使其更加简洁:

inline QLatin1String operator""_ql1( const char* str, std::size_t len ) { return QLatin1String( str, len ); }
...
filemodel -> setNameFilters( { "*.png"_ql1, "*.jpeg"_ql1, "*.jpg"_ql1, 
                               "*.gif"_ql1, "*.raw"_ql1 } );
© www.soinside.com 2019 - 2024. All rights reserved.