QProcess 使用

来源:互联网 发布:qq头像源码大全 编辑:程序博客网 时间:2024/05/29 18:20

QProcess类用于启动另一个外部应用程序,并可与之进行通信。该类的运行方式是异步的。QProcess类在外部进程拥有数据或完成时发送一个信号以通知相关的对象。

QProcess的使用模板如下:

  1. class XXX : public XXXX  
  2. {  
  3.      Q_OBJECT  
  4. …  
  5. private slots:  
  6.      void errorHandler(QProcess::ProcessError);  
  7.      void catchOutput();  
  8.      void catchError();  
  9.      void stateMonitor(QProcess::ProcessState newState);  
  10.      void slotStarted();  
  11.      void slotFinished(int, QProcess::ExitStatus);  
  12. …  
  13. private:  
  14.      QProcess p;  
  15. …  
  16. };  
  17.   
  18. XXX::XXX(…)  
  19. {  
  20. …  
  21. connect(&p, SIGNAL(started()), SLOT(slotStarted()));  
  22. connect(&p, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(slotFinished(int, QProcess::ExitStatus));  
  23. connect(&p, SIGNAL(error(QProcess::ProcessError)), SLOT(errorHandler (QProcess::ProcessError)));  
  24. connect(&p, SIGNAL(readyReadStandardError()), SLOT(catchError()));  
  25. connect(&p, SIGNAL(readyReadStandardOutput()), SLOT(catchOutput()));  
  26. …  
  27. }  
    1. XXX:: slotStarted()  
    2. {  
    3.    qDebug()<<”process has started”;  
    4. }  
    5.   
    6. XXX:: slotFinished(int exitcode, QProcess::ExitStatus status)  
    7. {  
    8.     if (exitStatus == QProcess::CrashExit) {  
    9.        …;  

     

    1.     } else {  
    2.        …;  
    3.     }  
    4. }  
    5.   
    6. XXX:: errorHandler(QProcess::ProcessError error)  
    7. {  
    8.         if (error == QProcess::FailedToStart) {  
    9.                   …  
    10.         }  
    11.        else if( error == QProcess:: Crashed )  
    12.        {  
    13.              …  
    14.        }  
    15.        else if( error == QProcess:: Timedout )  
    16.        {  
    17.           …  
    18.        }  
    19.        else if( error == QProcess:: WriteError )  
    20.       {  
    21.           …  
    22.        }  
    23.       else if( error == QProcess::ReadError )  
    24.       {  
    25.         …  
    26.       }  
    27.       else if( error == QProcess:: UnknownError )  
    28.       {  
    29.          …  
    30.        }  
    31. }  
    32.   
    33. XXX:: catchError()  
    34. {  
    35.       QByteArray newData = process.readAllStandardError();  
    36.      …  
    37.   
    38. }  
    39.   
    40. XXX::catchOutput()  
    41. {  
    42.       QByteArray newData = process.readAllStandardOutput();  
    43.    …  
    44. }  
      

 

 

0 0
原创粉丝点击