Qt中利用QProcess调用外部cmd.exe执行程序

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";;
    else
        qDebug() << "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;
}  

  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值