mainwindow.cpp文件:
--------------------------------
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextCodec>
#include <QCloseEvent>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//Qt对中文支持
QTextCodec *codec = QTextCodec::codecForName("GB2312");
QTextCodec::setCodecForLocale(codec);
process = new QProcess(this);
connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(start_read_output()));
connect(process, SIGNAL(readyReadStandardError()), this, SLOT(start_read_err_output()));
connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finish_process(int, QProcess::ExitStatus)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked(){
QString exe;
//exe = "test.bat";//要启动的程序
exe = "test.bat";
QStringList args;
//args<<"ping"<<"www.baidu.com";//要传递的参数
args<<"";
process->start(exe,args);
if (false == process->waitForStarted()){
ui->textBrowser->append("Process call failed!");
}else{
ui->textBrowser->append("Process call successed!");
}
}
void MainWindow::finish_process(int exitCode, QProcess::ExitStatus exitStatus){
if (exitStatus == QProcess::NormalExit){
ui->textBrowser->append("process exit normal");
}
else{
ui->textBrowser->append("process exit crash");
}
ui->textBrowser->append("process finised");
}
void MainWindow::start_read_output(){
QByteArray ba = process->readAllStandardOutput();
ui->textBrowser->append(QString::fromLocal8Bit(ba));
}
void MainWindow::start_read_err_output(){
QByteArray ba = process->readAllStandardError();
ui->textBrowser->append(QString::fromLocal8Bit(ba));
}
void MainWindow::closeEvent(QCloseEvent *event){
process->kill();
if(!process->waitForFinished(100))
return;
event->accept();
}
-----------------------------------------------------------------------------------------------------------------------------------------------
mainwindow.h文件:
-----------------------------
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QProcess>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QProcess* process;
protected:
void closeEvent(QCloseEvent *);
private slots:
void on_pushButton_clicked();
void start_read_output();
void start_read_err_output();
void finish_process(int exitCode, QProcess::ExitStatus exitStatus);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
---------------------------------------------------------------------------------------------------------------------------------------------------
测试方法:
在Qt的Ui中放置一个textBrowse和pushButton,并且在程序目录中创建一个test.bat文件,文件内容为:ping www.baidu.com
输出结果: