本文参考自QProcess的官方文档的Detailed Description。
当外部程序有新的标准输出数据可用时,QProcess会发出readyReadStandardOutput()信号,接收到这个信号后,我们可以使用readAllStandardOutput()来获取输出。
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class QPushButton;
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
private slots:
void clickSlot();
private:
QPushButton *pushButton;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include <QPushButton>
#include <QCoreApplication>
#include <QDebug>
#include <QProcess>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->resize(400, 300);
pushButton = new QPushButton(this);
pushButton->setText("PushButton");
pushButton->show();
connect(pushButton, &QPushButton::clicked, this, &Widget::clickSlot);
}
void Widget::clickSlot()
{
qDebug() << "[main process ID: " << QCoreApplication::applicationPid() << "]\n";
QProcess *process = new QProcess;
QString program = "C:/Users/jz/Desktop/untitled13.exe";
connect(process, &QProcess::readyReadStandardOutput, this, [=]()
{
qDebug() << process->readAllStandardOutput();
});
connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [ = ](int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug() << "untitled13.exe process finish." << exitCode << exitStatus;
});
process->start(program);
qDebug() << "[untitled13.exe process ID: " << process->processId() << "]";
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
生成外部程序untitled13.exe的代码:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int i = 0;
while (i < 10)
{
cout << ++i << endl;
Sleep(1000);
}
return 0;
}
输出结果:
图中1~10是逐秒输出的,符合我们的预期。