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,可以自行替换

相关推荐
小杍随笔17 小时前
【在 Rust + Tauri 2 应用中实现语言切换功能:完整技术指南】
开发语言·后端·rust
minji...17 小时前
Linux 网络基础之UDP协议(四)传输层协议 UDP,再谈端口号,UDP 特点
linux·服务器·开发语言·网络·c++·tcp/ip·udp
逻辑驱动的ken17 小时前
Java高频面试考点场景题27
java·开发语言·面试·职场和发展·求职招聘
清水白石00817 小时前
从手写初始化到 pytest fixture:让 Python 测试既干净、可复用,又能驾驭异步并发
开发语言·python·pytest
不知名的老吴17 小时前
关于C++中new的基本使用方法介绍
开发语言·c++
在角落发呆17 小时前
c socket 服务器转发,c socket 服务器转发的方法
服务器·c语言·开发语言
yujunl17 小时前
U9一种客开方案的解决
开发语言
wjs202417 小时前
Python pass 语句详解
开发语言
专注VB编程开发20年17 小时前
专业分析python底层调用与按键精灵,ah3等的对比,hookdll,内存加载,调用.net dll
开发语言·javascript·python·microsoft·php·.net