QT批量修改文件名
##话不多说直接上代码!
#include "BatchName.h"
#include <QPushButton>
#include <QFileDialog>
#include <qDebug>
#include <QStringList>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#pragma execution_character_set("utf-8")
BatchName::BatchName(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
connect(ui.btn_Choice, &QPushButton::clicked, this, &BatchName::btn_Choice_Clice);
}
void BatchName::btn_Choice_Clice() {
qDebug() << "弹出窗口打开多个文件";
//要删除文件名中的哪些字符
QStringList Filtr = this->ui.txt_FiltrStr->text().split(",");
//通过哪些名字拆分
QStringList Term = this->ui.txt_TermStr->text().split(",");
QStringList str_path_list = QFileDialog::getOpenFileNames(this, tr("选择图像文件"), tr("/file"), tr("图像文件(*.jpg *.png);;所有文件(*.*);;"));
this->ui.pb_Progress->setMaximum(str_path_list.size());
for (int i = 0; i < str_path_list.size(); i++) {
QString str_path = str_path_list[i];
QFile s_file(str_path);
QFileInfo picinfo(s_file);
QString fileDir = picinfo.path();
QString fileName = picinfo.fileName();
//这里先把要过滤的字符过滤完
for (int s = 0; s < Filtr.count(); s++)
{
fileName.replace(Filtr.at(s), "");
fileName.remove(QRegExp("\\s"));
}
qDebug() << fileDir << fileName;
QStringList nameList1 = fileName.split("kV");
if (nameList1.count() != 2)
{
QMessageBox::warning(this, "错误提示", "没有找到关键词,任务失败!");
return;
}
//第一次获取到是多少kv的
QString typeKv = nameList1.at(0);
//第二次从号塔分开,那么前面的需要处理,后面的就不用处理了
QStringList nameList2 = this->findTName(Term, nameList1.at(1));
if (nameList2.count() != 2)
{
QMessageBox::warning(this, "错误提示", "没有找到关键词,任务失败!");
return;
}
//状态及后缀名
QString toWerStatus = nameList2.at(1);
//把线路名与数字分开
QString roud = nameList2.at(0);
QString num,rname;
for (int j = 0; j < roud.length(); j++)
{
if (roud[j] >= '0' && roud[j] <= '9') {
num.append(roud[j]);
}
else {
rname.append(roud[j]);
}
}
QString newFileName = QString("%1/%2kV%3_%4#%5_%6").arg(fileDir).arg(typeKv).arg(rname).arg(rname).arg(num).arg(toWerStatus);
bool b = QFile::rename(str_path, newFileName);
if (!b) {
QMessageBox::warning(this, "错误提示", QString("任务%1失败!").arg(fileName));
}
this->ui.pb_Progress->setValue(i + 1);
}
}
QStringList BatchName::findTName(QStringList tname,QString str) {
QStringList re;
for (int i = 0; i < tname.count(); i++)
{
QString name = tname.at(i);
re = str.split(name);
if (re.count() < 2)
{
continue;
}
else if (re.count() > 2) {
QString joinstr;
QStringList nre;
for each (QString str in re)
{
int s = re.indexOf(str);
if (s == 0) {
nre.append(re.at(s));
}
else {
joinstr.append(re.at(s));
if (s != re.count() - 1)
{
joinstr.append(name);
}
}
qDebug() << str << s;
}
nre.append(joinstr);
re.clear();
re = nre;
}
else
{
break;
}
}
return re;
}