QProcess 进程间交互

#ifndef MAINWINDOW_H  
#define MAINWINDOW_H  
 
#include <QtGui>  
 
class MainWindow : public QMainWindow  
{  
    Q_OBJECT  
 
public:  
    MainWindow(QWidget *parent = 0);  
    ~MainWindow();  
 
private slots:  
    void openProcess();  
    void readResult(int exitCode);  
 
private:  
    QProcess *p;  
};  
 
#endif // MAINWINDOW_H
#include "mainwindow.h"  
 
MainWindow::MainWindow(QWidget *parent)  
    : QMainWindow(parent)  
{  
    p = new QProcess(this);  
    QPushButton *bt = new QPushButton("execute notepad", this);  
    connect(bt, SIGNAL(clicked()), this, SLOT(openProcess()));  
}  
 
MainWindow::~MainWindow()  
{  
 
}  
 
void MainWindow::openProcess()  
{  
    p->start("cmd.exe", QStringList() << "/c" << "dir");  
    connect(p, SIGNAL(finished(int)), this, SLOT(readResult(int)));  
}  
 
void MainWindow::readResult(int exitCode)  
{  
    if(exitCode == 0) {  
        QTextCodec* gbkCodec = QTextCodec::codecForName("GBK");  
        QString result = gbkCodec->toUnicode(p->readAll());  
        QMessageBox::information(this, "dir", result);  
    }  
}

       我们仅增加了一个 slot 函数。在按钮点击的 slot 中,我们通过 QProcess::start() 函数运行了指令

               cmd.exe /c dir

      这里是说,打开系统的 cmd 程序,然后运行 dir 指令。如果有对参数 /c 有疑问,只好去查阅 Windows 的相关手册了哦,这已经不是 Qt 的问题了。然后我们 process 的 finished() 信号连接到新增加的 slot 上面。这个 signal 有一个参数 int。我们知道,对于 C/C++ 程序而言,main() 函数总是返回一个 int,也就是退出代码,用于指示程序是否正常退出。这里的 int 参数就是这个退出代码。在 slot 中,我们检查退出代码是否是0,一般而言,如果退出代码为0,说明是正常退出。然后把结果显示在 QMessageBox 中。怎么做到的呢?原来,QProcess::readAll() 函数可以读出程序输出内容。我们使用这个函数将所有的输出获取之后,由于它的返回结果是 QByteArray 类型,所以再转换成 QString 显示出来。另外注意一点,中文本 Windows 使用的是 GBK 编码,而 Qt 使用的是 Unicode 编码,因此需要做一下转换,否则是会出现乱码的,大家可以尝试一下。

猜你喜欢

转载自blog.csdn.net/lengyuezuixue/article/details/81432870