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

相关推荐
专注VB编程开发20年27 分钟前
javascript的类,ES6模块写法在VSCODE中智能提示
开发语言·javascript·vscode
黄雪超8 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice8 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变8 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
lijingguang8 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
¥-oriented9 小时前
【C#中路径相关的概念】
开发语言·c#
CoderCodingNo9 小时前
【GESP】C++四级考试大纲知识点梳理, (7) 排序算法基本概念
开发语言·c++·排序算法
恋猫de小郭9 小时前
Meta 宣布加入 Kotlin 基金会,将为 Kotlin 和 Android 生态提供全新支持
android·开发语言·ios·kotlin
JosieBook9 小时前
【Java编程动手学】使用IDEA创建第一个HelloJava程序
java·开发语言·intellij-idea
Thomas_YXQ9 小时前
Unity3D DOTS场景流式加载技术
java·开发语言·unity