作用:QProcess类用于启动外部程序,并可以和外部程序进行通信。
继承于QIODevice类,因此可以被视为一个顺序I/O设备。
常用枚举:
ProcessState:NotRunning,Starting,Running.(完整流程Starting->Running->NotRunning)
常用函数:
启动外部程序(当主程序关闭时,外部程序也会关闭)
void start(const QString &program, const QStringList &arguments, QIODevice::OpenMode mode = ReadWrite)
void start(const QString &command, QIODevice::OpenMode mode = ReadWrite)
void start(QIODevice::OpenMode mode = ReadWrite)
?启动外部程序(当主程序关闭时,外部程序不会关闭)
bool startDetached(qint64 *pid = nullptr)
常用信号:
//错误发生
void errorOccurred(QProcess::ProcessError error)
//进程结束
void finished(int exitCode, QProcess::ExitStatus exitStatus)
//进程有错误数据
void readyReadStandardError()
//进程有标准的输出
void readyReadStandardOutput()
//已经开始
void started()
//状态改变
void stateChanged(QProcess::ProcessState newState)
demo代码:
//头文件
#include <QProcess>
#include <QDebug>
//我自定义的按钮槽函数
void QProcessDemo::on_pushButton_clicked()
{
QProcess *myProcess = new QProcess(this);
connect(myProcess, &QProcess::started, this, &QProcessDemo::onQProcessStarted);
connect(myProcess, &QProcess::stateChanged, this,&QProcessDemo::onQProcessStateChanged);
connect(myProcess, &QProcess::errorOccurred, this, &QProcessDemo::onQProcessErrorOcurred);
connect(myProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
[=](int exitCode, QProcess::ExitStatus exitStatus) {
qDebug() << exitCode << exitStatus;
});
myProcess->start("D://Program Files//Modbus Tools//Modbus Tools//Modbus Poll//mbpoll.exe", QStringList() << "");
}
//下面的是信号对应的槽函数,没有写全
void QProcessDemo::onQProcessStarted()
{
qDebug() << "QProcess started";
}
void QProcessDemo::onQProcessStateChanged(QProcess::ProcessState newState)
{
qDebug() << "QProcess current state:" << newState;
}
void QProcessDemo::onQProcessErrorOcurred(QProcess::ProcessError error)
{
qDebug() << "QProcess errorOcurred:" << error;
}
测试输出:
QProcess current state: QProcess::Starting QProcess current state: QProcess::Running QProcess started QProcess current state: QProcess::NotRunning 0 QProcess::NormalExit
|