以下指令 100% 有效:
这个方法QString QDirIterator::next() 将迭代器前进到下一个条目,并返回这个新条目的“文件路径”。如果hasNext()返回false,这个函数什么也不做,返回一个null QString。
如果QDirIterator 找到具有特定filter 的文件(基于const QStringList &nameFilters 参数),则QDirIterator::next() 返回“文件路径”,您无法将整个“文件路径”与“跳过文件夹”进行比较迭代!
因此,我不得不编写一个函数作为目录解析器,如下所示:
QStringList Widget::getCurrDirsOfFile(const QFileInfo &file_info, const QString &default_folder)
{
QString file_path = file_info.filePath();
QString file_name = file_info.fileName();
file_path.truncate(file_path.lastIndexOf("/" + file_name));
file_path = file_path.mid(file_path.lastIndexOf("/") + 1);
return file_path;
}
此函数获取“文件路径”并返回最后一个“文件夹名称”,如下所示:
input : /home/msi/Desktop/123/untitled/123/widget.h
output(list) : 123, 123
我们有 QString skiped_dir("untitled"); 作为跳过的文件夹!
在这种状态下,当您得到不包括123“文件夹名称”的内容时,您可以将该文件附加到QStringList filenames:
if(folder_list.indexOf(QRegExp(skiped_dir)) == -1)
filenames.append(it.filePath());
所以试试这个(cmets 中的通知):
void Widget::btn_iterate_clicked()
{
// folder to iterate
QString folder("/home/msi/Desktop/");
// folder-name you want to skip
QString skiped_dir("untitled");
// file-names which are match with .h filter stored in filenames list
QStringList filenames;
// this list used in QStringList getCurrDirsOfFile() method
QStringList folder_list;
// iterator
QDirIterator it(folder, QStringList() << "*.h" , QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()) // if next object exist for iterate
{
// we have the file with .h extension
it.next();
// get previous folders that exist in filepath address of it.fileInfo()
folder_list = getCurrDirsOfFile(it.fileInfo(), folder);
// if folder_list contained skiped folder then reject that or appent it
if(folder_list.indexOf(QRegExp(skiped_dir)) == -1)
filenames.append(it.filePath());
}
for(int i = 0;i < filenames.count();i++)
{
QMessageBox::information(this, "", filenames.at(i));
}
}
假设我们有下面的树(目录):
这个程序只是显示:
/home/msi/Desktop/build-untitled-Desktop_Qt_5_0_2_GCC_64bit-Debug/ui_widget.h
/home/msi/Desktop/1/1.h