亲宝软件园·资讯

展开

Qt一个进程运行另一个进程

MechMaster 人气:0

1. 一个进程运行另一个进程

2. 例程代码

在这里插入图片描述

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();

private slots:
    void on_pushButton_clicked();

    void showResult();
    void showState(QProcess::ProcessState state);
    void showError();
    void showFinished(int,QProcess::ExitStatus);

private:
    Ui::MainWindow *ui;

    QProcess myProcess;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QTextCodec>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //添加信号和槽的关联
    connect(&myProcess,&QProcess::readyRead,this,&MainWindow::showResult);
    connect(&myProcess,&QProcess::stateChanged,this,&MainWindow::showState);
    connect(&myProcess,&QProcess::errorOccurred,this,&MainWindow::showError);
    connect(&myProcess,SIGNAL(finished(int,QProcess::ExitStatus)),
                              this,SLOT(showFinished(int,QProcess::ExitStatus)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    //启动记事本程序,由于它在Windows的系统目录下,该目录已经加在了系统PATH环境变量中,所以不需要写具体路径
    //myProcess.start("notepad.exe");

    QString program = "cmd.exe";
    QStringList arguments;
    arguments<<"/c dir&pause";
    myProcess.start(program,arguments);
}

void MainWindow::showResult()
{
    QTextCodec * codec = QTextCodec::codecForLocale();
    qDebug()<<"showResult: "<<endl<<codec->toUnicode(myProcess.readAll());
}

void MainWindow::showState(QProcess::ProcessState state)
{
    qDebug()<<"showState: ";
    if(state == QProcess::NotRunning)
    {
        qDebug()<<"No Running";
    }
    else if(state == QProcess::Starting)
    {
        qDebug()<<"Starting";
    }
    else
    {
        qDebug()<<"Running";
    }
}

void MainWindow::showError()
{
    qDebug()<<"showError:"<<endl<<myProcess.errorString();
}

void MainWindow::showFinished(int exitcode, QProcess::ExitStatus exitStatue)
{
    qDebug()<<"showFinished:"<<endl<<exitcode<<exitStatue;
}

加载全部内容

相关教程
猜你喜欢
用户评论