c++qtqt5qdir

How to capture parent directory from lambda


In my code I list subdirectories name(only child dir) and if i click this subdirectory , the images inside this subdir will be displayed. In my case I cant capture parent directory from inside lambda. How can I do that?

Dir directory = QFileDialog::getExistingDirectory(this, tr("Open Directory"),"/home",

                                                   QFileDialog::ShowDirsOnly| QFileDialog::DontResolveSymlinks);
for (const QFileInfo &finfo: directory.entryInfoList()) {
    QDir dir(finfo.absoluteFilePath());
    ui->listWidget_dirs->addItem(dir.dirName());
}

//QStringList files = directory.entryList(QDir::Dirs);
//ui->listWidget_dirs->addItems(files);

auto listWidget_images = new QListWidget();//set listwidget to display images
listWidget_images->setMinimumSize(1200,400);
listWidget_images->setViewMode(QListWidget::IconMode);
listWidget_images->setIconSize(QSize(320,240));
listWidget_images->setResizeMode(QListWidget::Adjust);




connect(ui->listWidget_dirs, & QListWidget::itemClicked,[listWidget_images,this](QListWidgetItem *item)
{
    listWidget_images->show();
    listWidget_images->clear();
   /*this is where it is wrong*/ QDir path(directory + '/' + item->text());
    path.setNameFilters({"*.png", "*.jpg"});
    for(const QFileInfo & finfo: path.entryInfoList()){
        QListWidgetItem *item = new QListWidgetItem(QIcon(finfo.absoluteFilePath()), finfo.fileName());
        listWidget_images->addItem(item);

    }
});

Solution

  • I just wanted to leave a note. Be sure that your objects alive during your lamda exist, especially listWidget_images. If you delete it elsewhere, your lamda will crash. I would recommment to change the connect line a little:

    from

    connect(ui->listWidget_dirs, & QListWidget::itemClicked,[directory,listWidget_images, this](QListWidgetItem *item)
    

    to

    connect(ui->listWidget_dirs, & QListWidget::itemClicked, listWidget_images, [directory,listWidget_images, this](QListWidgetItem *item)
    

    If you put the pointer listWidget_images before the capture list [] the lamda will be destroyed, when the object from listWidget_images is destroyed. Otherwise your application will crash in the first line of your lamda if the object doesn't exist anymore.