下面我們再看一個更復雜的例子,調用一個系統命令,這里我使用的是 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