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

前言

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

效果:

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

源码demo:

非完整代码:

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

相关推荐

  1. QtQt通过QProcess::execute()调用echo命令不生效

    2024-03-10 00:04:07       51 阅读
  2. neo4j如何并列执行命令

    2024-03-10 00:04:07       53 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-10 00:04:07       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-10 00:04:07       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-10 00:04:07       82 阅读
  4. Python语言-面向对象

    2024-03-10 00:04:07       91 阅读

热门阅读

  1. QT学习笔记2--QT简述

    2024-03-10 00:04:07       50 阅读
  2. LeetCode 2710.移除字符串中的尾随零

    2024-03-10 00:04:07       40 阅读
  3. 力扣 239. 滑动窗口最大值

    2024-03-10 00:04:07       44 阅读
  4. P10095 [ROIR 2023 Day 1] 斐波那契乘积

    2024-03-10 00:04:07       67 阅读
  5. Druid数据库连接池配置

    2024-03-10 00:04:07       47 阅读
  6. 国内用ChatGPT可以吗

    2024-03-10 00:04:07       46 阅读
  7. Xargs命令详解: 构建和执行命令的必备工具

    2024-03-10 00:04:07       49 阅读
  8. 面试经典150题(101-104)

    2024-03-10 00:04:07       44 阅读
  9. 一个简单的HTML 个人网页

    2024-03-10 00:04:07       44 阅读
  10. 【记录31】elementUI el-tree 虚线、右键、拖拽

    2024-03-10 00:04:07       43 阅读