1. 程式人生 > >Qt呼叫外部程式

Qt呼叫外部程式

一、呼叫系統預設應用開啟檔案

使用QDesktopServices的openUrl()成員

這個函式是跨平臺的,Qt會根據不同的系統平臺呼叫預設的程式開啟指定檔案,QUrl存放制定的路徑,使用非常簡便,示例程式碼如下:

QString fileName=QFileDialog::getSaveFileName(this,tr("儲存"), QCoreApplication::applicationDirPath()+"/socketReport", "Text files(*.txt)");
QDesktopServices::openUrl(QUrl(fileName));

兩行開啟程式碼就能實現使用預設外部程式開啟指定的txt檔案。

又比如,開啟一個網頁:

QDesktopServices::openUrl(QUrl(QString("http://www.baidu.com/")));//呼叫系統的預設瀏覽器開啟百度主頁

二、指定外部程式開啟指定檔案

使用QProcess解決:

·(1)直接呼叫QProcess::execute()靜態成員

    QStringList args;
    args<<QDir::homePath()+QString("/test.txt");
    QProcess::execute(QString("gedit"),args);//參1位應用程式名,參2為命令引數

(2建立QProcess物件,呼叫start()
    QString appName=QCoreApplication::applicationDirPath()+"/tools/tcpServer/TcpServer_Test.exe";
    QProcess *toolProcess = new QProcess;
    toolProcess->start(appName);
</pre><span style="font-size:12px;"> 注:1.方法(2)還可使用waitForStarted()和waitForFinished()進行精細控制,詳見Qt Assistant</span><p></p><p><span style="font-size:12px;"><span style="white-space:pre"></span>       2.方法(1)會阻塞Qt本應用,直到呼叫的外部程式關閉,而方法(2)不會</span></p><p></p><p></p><p><span style="font-size:12px"><span style="white-space:pre"></span></span></p><p><span style="font-size:12px"><span style="white-space:pre"></span>一個帶介面的示例程式如下:</span></p><p><span style="font-size:12px"></span></p><pre name="code" class="cpp">#include "dialog.h"
#include "ui_dialog.h"

#include <QProcess>
#include <QStringList>
#include <QDir>
#include <QFileDialog>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    ui->pushButton->setEnabled(false);
    ui->pushButton_2->setEnabled(false);

}

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

void Dialog::on_pushButton_clicked()
{
    QString inputName=ui->lineEdit->text();
    if(inputName.isEmpty())
        inputName=QDir::homePath();
    QString fileName=QFileDialog::getOpenFileName(this,tr("Open"),inputName,tr("text(*.txt *.c *.h *.cpp *.sh)"));
    if(!fileName.isEmpty())
    {
        ui->lineEdit->setText(fileName);
        ui->pushButton_2->setEnabled(true);
    }
}

void Dialog::on_lineEdit_textChanged(const QString &arg1)
{
    ui->pushButton->setEnabled(true);
}

void Dialog::on_pushButton_2_clicked()
{
    QString fileName=ui->lineEdit->text();
    QProcess::execute(QString("notepad"),QStringList()<<fileName);
}


執行效果如下: