通过递归遍历添加子项到treewidget中,测试代码已通过,举例为遍历添加/home/XXX下所有文件。解析和详细代码如下:
1.首先在main函数中创建目录根项。
QString rootpath="/home/XXX";
QTreeWidgetItem* root = new QTreeWidgetItem(QStringList()<<rootpath);
root->setIcon(0, QIcon(":/file/image/link.ico"));
root->setCheckState(1, Qt::Checked);
allfile(root,rootpath); //遍地添加/home/XXX目录下所有文件,此函数具体内容如下
2.遍历添加详细函数
QFileInfoList MainWindow::allfile(QTreeWidgetItem *root,QString path) //参数为主函数中添加的item和路径名
{
/*添加path路径文件*/
QDir dir(path); //遍历各级子目录
QDir dir_file(path); //遍历子目录中所有文件
dir_file.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); //获取当前所有文件
dir_file.setSorting(QDir::Size | QDir::Reversed);
QFileInfoList list_file = dir_file.entryInfoList();
for (int i = 0; i < list_file.size(); ++i) { //将当前目录中所有文件添加到treewidget中
QFileInfo fileInfo = list_file.at(i);
QString name2=fileInfo.fileName();
QTreeWidgetItem* child = new QTreeWidgetItem(QStringList()<<name2);
child->setIcon(0, QIcon(":/file/image/link.ico"));
child->setCheckState(1, Qt::Checked);
root->addChild(child);
}
QFileInfoList file_list=dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
QFileInfoList folder_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); //获取当前所有目录
for(int i = 0; i != folder_list.size(); i++) //自动递归添加各目录到上一级目录
{
QString namepath = folder_list.at(i).absoluteFilePath(); //获取路径
QFileInfo folderinfo= folder_list.at(i);
QString name=folderinfo.fileName(); //获取目录名
QTreeWidgetItem* childroot = new QTreeWidgetItem(QStringList()<<name);
childroot->setIcon(0, QIcon(":/file/image/link.ico"));
childroot->setCheckState(1, Qt::Checked);
root->addChild(childroot); //将当前目录添加成path的子项
QFileInfoList child_file_list = allfile(childroot,namepath); //进行递归
file_list.append(child_file_list);
file_list.append(name);
}
return file_list;
}
效果如图所示:
转载 linux国富