QT中使用QProcess执行命令,实时获取数据,例如进度条

前言

因为之前写了一个接收和发送文件的脚本,然后又需要获取进度,同步到进度条中。

效果:

使用正则匹配,获取命令行命令中的以下数据,然后同步到进度条

源码demo:

非完整代码:

cpp 复制代码
#include <QRegularExpression>
#include <QProcess>

bool transferFile(const QString &localFilePath, const QString &remoteFilePath, const QString &host, const QString &username, const QString &password)
{
    ui->sendProgressBar->setValue(0);
    QRegularExpression re("(\\d{1,3})%"); // 匹配1到3位数字后面跟着一个百分号

    QProcess process;
    QString  appPath;
    if(sendFileShPath.endsWith("/")){
        appPath = sendFileShPath + "send_file";
    }else{
        appPath = sendFileShPath + "/send_file";
    }

    QString  cmd = QString("%6 %1 %2 %3 %4 %5")
            .arg(username).arg(host).arg(password).arg(localFilePath).arg(remoteFilePath).arg(appPath);

    process.start(cmd);
    qDebug()<<QString("%1  send to  %2").arg(localFilePath).arg(remoteFilePath);

    // 当有标准输出可读时,读取并输出内容
    QObject::connect(&process, &QProcess::readyRead, [&]() {
        while (!process.atEnd()) {
            QByteArray ba = process.readLine();
            QString s = QString::fromUtf8(ba).trimmed();
            QRegularExpressionMatch match = re.match(s);
            if(match.captured(1) != ""){
                int curNum = match.captured(1).toInt();
                qDebug() << curNum <<"%";
                ui->sendProgressBar->setValue(curNum);
            }
        }
    });

    if (!process.waitForStarted()) {
        qDebug() << "Failed to start process.";
        return false;
    }

    process.waitForFinished();

    return true;
}

以上代码中的cmd,可以自行替换

相关推荐
I'mChloe5 小时前
PTO-ISA 深度解析:PyPTO 范式生成的底层指令集与 NPU 算子执行的硬件映射
c语言·开发语言
编程小白20266 小时前
从 C++ 基础到效率翻倍:Qt 开发环境搭建与Windows 神级快捷键指南
开发语言·c++·windows·qt·学习
深蓝海拓6 小时前
PySide6,QCoreApplication::aboutToQuit与QtQore.qAddPostRoutine:退出前后的清理工作
笔记·python·qt·学习·pyqt
像风一样的男人@6 小时前
python --读取psd文件
开发语言·python·深度学习
输出输入6 小时前
前端核心技术
开发语言·前端
加油,小猿猿6 小时前
Java开发日志-双数据库事务问题
java·开发语言·数据库
薛定谔的猫喵喵6 小时前
天然气压力能利用系统综合性评价平台:基于Python和PyQt5的AHP与模糊综合评价集成应用
开发语言·python·qt
独好紫罗兰6 小时前
对python的再认识-基于数据结构进行-a004-列表-实用事务
开发语言·数据结构·python
gjxDaniel6 小时前
Objective-C编程语言入门与常见问题
开发语言·objective-c
choke2337 小时前
[特殊字符] Python异常处理
开发语言·python