1、#include "mainwindow.h"中
添加头文件:
#include <QProcess>
添加成员:
QProcess *myprocess;
添加槽函数声明:
void showCMDResult();
void showCMDState(QProcess::ProcessState state);
void showCMDError();
void showCMDFinished(int exitCode, QProcess::ExitStatus exitStatus);
2、mainwindow.cpp中
构造函数中实例化:
myprocess = new QProcess;
添加槽函数:
connect(myprocess, SIGNAL(readyRead()), this, SLOT(showCMDResult()));
connect(myprocess, SIGNAL(stateChanged(QProcess::ProcessState)),this, SLOT(showState(QProcess::ProcessState)));
connect(myprocess, SIGNAL(error(QProcess::ProcessError)),this, SLOT(showCMDError()));
connect(myprocess, SIGNAL(finished(int,QProcess::ExitStatus)),this, SLOT(showCMDFinished(int, QProcess::ExitStatus)));
实现槽函数:
void MainWindow::showCMDResult()
{QString strTemp=QString::fromLocal8Bit(myprocess->readAll());ui->textEdit->append(strTemp);
}void MainWindow::showCMDState(QProcess::ProcessState state)
{if(state==QProcess::NotRunning)qDebug() << "Not Running";else if(state==QProcess::Starting) qDebug() << "Starting";;elseqDebug() << "Running";
}void MainWindow::showCMDError()
{ui->textEdit->append(myprocess->errorString());
}void MainWindow::showCMDFinished(int exitCode, QProcess::ExitStatus exitStatus)
{ui->textEdit->append(QString("启动结束:").append("退出代码:").append(QString::number(exitCode)).append("退出状态:").append(QString::number((uint)exitStatus)));
}
3、启动cmd.exe
QStringList argument;
argument<<"/C"<<"python"<<ui->lineEdit_filepath->text()<<ui->lineEdit_inputpara->text();
myprocess->start("cmd.exe",argument);
ui->textEdit->append("启动cmd.exe");
// 等待进程启动
if (!myprocess->waitForStarted())
{ui->textEdit->append("启动失败");return;
}