一丶文件夹
1.创建文件夹
bool QDir::mkpath(const QString &dirPath) const
bool QDir::mkdir(const QString &dirName) const
重要的问题是mkpath和mkdir的区别,如果需要创建一个父目录不存在的目录,就使用mkpath,否则会导致新建文件夹不成功,下面是(在当前应用程序目录下创建一个test文件夹)
QString curPath=QCoreApplication::applicationDirPath(); //获取应用程序所在文件夹的路径
示例
QString str = "/test";
QString path = QCoreApplication::applicationDirPath();
QString test = path+str;
QDir *folder = new QDir;
//判断创建文件夹是否存在
bool exist = folder->exists(test);
if(exist)
{
QMessageBox::warning(this,tr("创建文件夹"),tr("文件夹已经存在!"));
}
else //如果不存在,创建文件夹
{
//创建文件夹
bool ok = folder->mkpath(test);
//判断是否成功
if(ok)
{
QMessageBox::warning(this,tr("创建文件夹"),tr("文件夹创建成功!"));
}
else
{
QMessageBox::warning(this,tr("创建文件夹"),tr("文件夹创建失败!"));
}
}
2.用户自己选择文件夹路径
QString dir_path=QFileDialog::getExistingDirectory(nullptr,"choose directory","C:/");
第一个参数是指定的父窗口
第二个参数是窗口的标题
第三个参数是初始从哪里开始查找
返回值为你选择的文件夹路径
3.获取文件夹下的子文件夹
QDir directory("D:/FastCharge"); // 替换为你的目录路径
QStringList subDirectories;
// 遍历所有子目录
for(const QFileInfo& info : directory.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot)){
if(info.isDir()){
subDirectories.append(info.absoluteFilePath());
qDebug() << "子目录名称:" << info.fileName(); // 获取子目录名称
}
}
// 输出所有子目录路径
for(const QString& subDir : subDirectories){
qDebug() << subDir;
}