调用一个系统命令,并读取它的输出值(使用QProcess.readAll)

下面我们再看一个更复杂的例子,调用一个系统命令,这里我使用的是 Windows,因此需要调用 dir;如果你是在 Linux 进行编译,就需要改成 ls 了。

mainwindow.h

#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

mainwindow.cpp

#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 编码,因此需要做一下转换,否则是会出现乱码的,大家可以尝试一下。

好了,进程间交互就说这么说,通过查看文档你可以找到如何用 QProcess 实现进程过程的监听,或者是令Qt 程序等待这个进程结束后再继续执行的函数。

本文出自 “豆子空间” 博客,请务必保留此出处http://devbean.blog.51cto.com/448512/305116

原文地址:https://www.cnblogs.com/findumars/p/5346318.html