QT笔记 - QProcess读取外部程序(进程)消息

简要介绍

QProcess 可用于在当前程序中启动独立的外部程序(进程),并进行通讯,通讯原理是通过程序的输入或输出流,即通过c中的printf()和或c++的std::cout等。

函数

  1. void QProcess**::start**(const QString & program, const QStringList & arguments = {}, OpenMode mode = ReadWrite)
  2. void QProcess**::** readyReadStandardOutput()
  3. QByteArray QProcess**::readAllStandardOutput** ()
  4. bool QProcess**::waitForFinished** (int msecs = 30000)

函数说明

  1. 启动目标程序。形参: program:目标程序启动目录,包含程序名称及后缀;arguments:参数,可以向目标程序的main()函数传递两个参数;mode:读写打开模式。
  2. 是个信号函数,目标程序有即时输出时触发,可用于接收目标程序的实时输出
  3. 读取输出
  4. 等待目标程序完成(退出) ,注意期间主程序会陷入冻结状态。形参:msec:等待时长,注意,该时间到期后将主动关闭目标程序,默认30000毫秒,-1时可无限时长等待。

示例

主程序:

cpp 复制代码
    QProcess process;
    // process.setProcessChannelMode(QProcess::MergedChannels);
    process.start("C:\\myapp\\ProcessTest.exe");

    // 实时读取
    process.connect(&process, &QProcess::readyReadStandardOutput, [&](){
        qDebug() << "main - " << process.readAllStandardOutput();
    });

    if(process.waitForFinished(-1)){
        qDebug() << "main - Process:\"" << process.program() << "\" Finished";
    }


    // // 或目标程序退出后读取全部
    // if(process.waitForFinished(-1)){
    //     qDebug() << "main - " << process.readAllStandardOutput();
    // } else {
    //     qDebug() << "main - 2";
    // }

目标程序:

复制代码
void Widget::on_pushButton_clicked()
{
    std::cout << "Widget::on_pushButton_clicked - " << ui->lineEdit->text().toStdString() << std::endl;
    std::cout << std::flush;
}

测试结果输出:

相关推荐
丰锋ff4 小时前
基于 Qt 的智能门禁系统(二)
开发语言·qt
fpcc4 小时前
跟我学C++中级篇——编译期的条件选择
开发语言·c++
xian_wwq4 小时前
【学习笔记】-深度认知系列-第2讲-大模型到底是什么?——拆解“参数、训练、推理”
笔记·学习·深度认知
SomeB1oody4 小时前
【RustyML入门】6.3. 并行归约
开发语言·后端·机器学习·rust·教程
mqiqe6 小时前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
lzhdim6 小时前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
脉动数据行情6 小时前
Java 实现台股 TWSE/TPEx 行情采集(个股 + K 线)
java·开发语言·twse·tpex·台股
爱学习的小邓同学6 小时前
Golang --- (1)第一个Golang程序
开发语言·后端·golang
zx_741484817 小时前
【Python 入门】面向对象基础:类、对象、成员变量与构造方法
开发语言·python
Oll Correct7 小时前
Adobe illustrator 案例九:百宝箱图标绘制
笔记·ui·adobe·illustrator