Qt 中用QProcess呼叫cmd命令

2022-07-01 12:15:17 字數 2316 閱讀 4450

專案做到一定階段,常常須要在原來的project上呼叫外部程式。

qt為此提供了qprocess類,qprocess可用於完畢啟動外部程式,並與之互動通訊。

基本用法:

qstring strtemp=qstring::fromlocal8bit(p.readallstandardoutput()); //獲得輸出

// qmessagebox testmassage;

// testmassage.settext(strtemp);

// testmassage.exec();另一種用法:

qprocess p(0);

qstring command = "e:/test_rar_course/rar.exe";

qstringlist args;

p.execute(command,args);//command是要執行的命令,args是引數

p.waitforfinished();

qdebug()<注:

qprocess::start() 接受兩個引數,第乙個是要執行的命令或者程式,這裡就是 notepad.exe;第二個是乙個 qstringlist 型別的資料,也就是需要傳遞給這個程式的執行引數。注意,這個程式是需要能夠由系統找到的,一般是完全路徑。

1-不帶空格。能夠啟動

2-帶空格,無法啟動

process->start("c:/program files/haozip/haozip.exe");

3-帶空格,使用帶參模式。能夠啟動

process->start("c:/program files/haozip/haozip.exe", qstringlist("c:/program files/haozip/haozip.exe"));
乙個完整的例子

mainwindow.h

#ifndef mainwindow_h  

#define mainwindow_h

#include class mainwindow : public qmainwindow

;

#endif // mainwindow_h

mainwindow.cpp

#include "mainwindow.h"  

mainwindow::mainwindow(qwidget *parent)

: qmainwindow(parent)

mainwindow::~mainwindow()

void mainwindow::openprocess()

void mainwindow::readresult(int exitcode)

}

在按鈕點選的 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 程式等待這個程序結束後再繼續執行的函式。

【更多參考】一、二、三、四

QT中呼叫外部程式 QProcess的使用

本文 http blog.csdn.net waderchan archive 2009 05 19 4199913.aspx 執行介面如下 程式共包含以下有乙個檔案 view plain copy to clipboard print?main.cpp include process.h incl...

QT中呼叫外部程式 QProcess的使用

程式共包含以下有乙個檔案 main.cpp include process.h include intmain intargc,char argv process.h ifndef process h define process h include classqlabel classqlineed...

Qt中的利用QProcess呼叫外部程式

今天工作中要qt呼叫記事本來開啟乙個檔案。上網查了一下用qprocess用法,一般的qprocess開啟外部程式.exe檔案,下面總結一下,挺簡單的。int qprocess execute const qstring program,const qstringlist arguments prog...