Qt调用外部程序

来源:互联网 发布:宜家海沃格床垫知乎 编辑:程序博客网 时间:2024/06/05 03:39

一、调用系统默认应用打开文件

使用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);}


运行效果如下:



1 0