QT4-外部程序调用的简单方法

来源:互联网 发布:沉迷galgame知乎 编辑:程序博客网 时间:2024/04/30 11:24

   QT4对于界面编程无疑是一个很方便的工具。但是由于它界面开发专项特性,可能导致了某些方面的不足(到目前为止暂时没有使用到这类复杂功能,所以只能是推测)。这样当整个程序需要某些功能时,就需要外部模块的支持。为了能够与外部程序相互联系,Qt4提供了强大的外部程序调用类。先说说QProcess类,目前主要用到程序调用函数。官方说明如下:

(引用自ttp://qt.nokia.com/doc/4.5/qprocess.html#execute-2)

  

#include <QProcess>

 

int QProcess::execute ( const QString & program, const QStringList & arguments )   [static]

Starts the program program with the arguments arguments in a new process, waits for it to finish, and then returns the exit code of the process. Any data the new process writes to the console is forwarded to the calling process.

The environment and working directory are inherited by the calling process.

On Windows, arguments that contain spaces are wrapped in quotes.

int QProcess::execute ( const QString & program )   [static]

This is an overloaded function.

Starts the program program in a new process. program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.

  

   这两个函数使用起来是很简单的,很方便就可以调用外部程序。

   但是有一点是值得注意的,当外部函数被调用以后,主程序的进程就会被调用的函数阻塞,导致无法继续对操作做出反映。要解决这个问题,可以利用QThread类为调用的外部程序建立一个新进程,建立方法如下:

 

例如需要在窗口中打开注册表编辑器

 

    1、明确打开文件的位置和名称,注册表编辑器名称为regedit

 

    2、建立一个类MyThread,用于继承QThread类,并声明虚函数run(),该函数用于程序调用该进程时自动调用。

       

       #include <QThread>

 

       class MyThread : public QThread

       {

        public

            void run();

       };

 

    3、在MyTread::run()函数中添加需要该进程执行的内容(本例子中要利用QProcess类调用regedit)

 

       #include <QProcess>

 

       void MyThread::run()

       {

            QProcess process;

 

            

            process.execute("regedit");

        }

 

     经过以上的处理后,在运行regedit的时候主窗口就不会因阻塞而无响应了。

 

     这只是个简单的实现外部函数调用的方法,至于进程如何同步的问题,还在继续研究中....