在我的代码中,我列出了子目录名称(只有子目录(,如果我单击这个子目录,就会显示这个子目录中的图像。在我的情况下,我无法从lambda内部捕获父目录。我该怎么做?
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);
}
});
我只是想留个便条。请确保您的对象在lamda期间是活动的,尤其是listWidget_images。如果你在其他地方删除它,你的lamda就会崩溃。我建议稍微改变一下连接线:
来自
connect(ui->listWidget_dirs, & QListWidget::itemClicked,[directory,listWidget_images, this](QListWidgetItem *item)
至
connect(ui->listWidget_dirs, & QListWidget::itemClicked, listWidget_images, [directory,listWidget_images, this](QListWidgetItem *item)
如果将指针listWidget_images放在捕获列表[]之前,则当listWidget_images中的对象被销毁时,lamda将被销毁。否则,如果对象不存在,应用程序将在lamda的第一行崩溃。
我知道怎么做了,这就是代码。
QDir 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());
}
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,[directory,listWidget_images, this](QListWidgetItem *item)
{
listWidget_images->show();
listWidget_images->clear();
// QDir path(item->text());
QDir dir = directory.absolutePath() + '/' + item->text();
dir.setNameFilters({"*.png", "*.jpg"});
for(const QFileInfo & finfo: dir.entryInfoList()){
QListWidgetItem *item = new QListWidgetItem(QIcon(finfo.absoluteFilePath()), finfo.fileName());
listWidget_images->addItem(item);
}
});