Qprocess Process Class-calling external programs

Source: Internet
Author: User
Tags error code exit in qt designer
qprocessThe Process class QT provides a qprocess class for starting and communicating with an external program, and it is very simple to start a new process by passing the program name and startup parameters to the start () function. For example:
    Qobject *parent;
    QString program = "Tar" 
    qstringlist arguments;
    Arguments << "CZVF" << "backup.tar.gz" << "Home";
    Qprocess *myprocess = new Qprocess (parent);
    Qprocess->start (program, arguments);

When the start () function is called, the myprocess process immediately enters the startup state, but the TAR program has not been called and cannot read or write standard input. When the process finishes booting, it enters the "running state" and emits a started () signal outward. In terms of input and output, Qprocess considers a process as a stream type I/O device. You can read and write a process like a network connection that uses the Qtcpsocket read-write stream type. You can write data to the standard input of the initiating process through the qiodevice::write () function, or through Qiodevice::read (), Qiodevice:: The ReadLine () and Qiodevice::getchar () functions read data from the standard output of this process. In addition, because qprocess is inherited from the Qiodevice class, because of level four, it can also be used as qxmlreader data in the source, or generate upload data for qftp. Finally, when the process exits, Qprocess enters the start state----"Non-operational state" and emits a finished () signal.
void finished (int exitCode, qprocess::exitstatus exitstatus)

The signal returns the exit code and exit status of the process exit in the parameter, you can call the ExitCode () function and the Exitstatus () function to get the two values of the last exit process, respectively. Where QT defines the process "exit state" only the normal exit and process crashes two kinds, The corresponding values are Qprocess::normalexit (value 0) and Qprocess::crashexit (value 1) respectively. When a process generates an error in the run, the qprocess emits an error () signal, which can be passed by calling error () The function returns the type that produced the error the last time, and through, State () to find out where the process is at this time. QT defines the following process error code:----------------------------------------------------------------
Error Constants                                 values        Description Qprocess::failedtostart        0        Process start failure qprocess::crashed                 1         crashes after successful start of process Qprocess::timedout               2         Last call to waitfor ... () function timed out. The qprocess state is not changed at this time, and can again             call WAITFOR () type of function Qprocess::writeerror               3        An error occurred while writing to the process. Qprocess::readerror            If the process has not started or the input channel is closed   4         read from the processAn error occurred while fetching data. Qprocess::unknownerror       5        When process is not started Unknown error. This is also the default value returned by the error () function.
Standard output of the process: stdout: Typically used for console-down output stderr: Typically used for process printing errors They are essentially two separate data streams.   The current read channel can be set by calling the Setreadchanned () function when there is readable data, QT emits a readyread () signal if the data is read in the standard output and standard error channels, and a readyreadstandardoutput () signal is emitted   A standard error also emits a readyreadstandarderror () signal readallstandardoutput () function reads data from a standard output channel Readallstandarderrot () function reads data from a standard error channel Calling the Setreadchannelmode () function with the Mergedchannels parameter before the process starts can combine the standard output channel with the standard input error channel:
#include <QApplication>
#include <QProcess>
#include <QString>
#include <iostream >

int main (int argc, char *argv[])
{
    qapplication app (argc, argv);

    qprocess proc;
    qstringlist arguments;
    Arguments << "-na";
    Proc.start ("netstat", arguments);

    Wait for the process to start
    if (!proc.waitforstarted ())
    {
        std::cout << "start failed \ n";
        return false;
    }
    Turn off the write channel because no data is written to the process, it is useless to 
    proc.closewritechannel ();

    Console output for the save process
    Qbytearray procoutput;
    Wait for process to end while
    (false = = proc.waitforfinished ())
    {
       std::cout << "End failed \ n";
       return 1;
    } 
    Read process output to console data 
   procoutput = Proc.readall ();
   Output read Data 
   std::cout << procoutput.data () << Std::endl;
   Returns the return 
   exit_success;
}
In order to deepen the use of the Qprocess class, Next, we will paste the code of a case that you have written: This case is a command window under the simulation DOS. " widget.hThe header file
#ifndef widget_h
#define WIDGET_H
#include <QProcess>
#include <QWidget>

namespace Ui {
    class Widget;
}

Class Widget:public Qwidget
{
    q_object public

:
    explicit Widget (Qwidget *parent = 0);
    ~widget ();

Private:
    ui::widget *ui;
    Qprocess *pro;//Creates a process object
    QString out;
Private slots:
    void on_pushbutton_clicked ();//Run button slot
    void Readoutput ();//Read data slot from Process
};

#endif//Widget_h

" Widget.cppThe source file
#include "widget.h"
#include "ui_widget.h"

widget::widget (Qwidget *parent):
    qwidget (Parent),
    UI ( New Ui::widget)
{
    ui->setupui (this);
    This->pro = new Qprocess;
    This->setwindowflags (qt::windowminimizebuttonhint);

    Qobject::connect (Ui->lineedit,signal (returnpressed ()), This,slot (on_pushbutton_clicked ()));
    Ui->lineedit signal and slot connection, the cursor in the Ui->lineedit, press ENTER to achieve the same as the Click Run button effect
    qobject::connect (Pro,signal (Readyread ( )), This,slot (Readoutput ()));
    The slot that triggers the output data when the data is ready to be read from the process
}

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

void widget::on_pushbutton_clicked ()
{
   QString cmd = Ui->lineedit->text ();
   Pro->start (cmd);
   out = TR ("");
   Ui->textedit->settext (out);
}

void Widget::readoutput ()
{out
   + = Pro->readall ();
   Ui->textedit->settext (out);
}

" main.cppThe source file
#include <QtGui/QApplication>
#include "widget.h"
#include <QTextCodec>
int main (int argc, Char *argv[])
{
    qapplication A (argc, argv);
    Qtextcodec::setcodecforcstrings (Qtextcodec::codecforname ("GBK"));
    Qtextcodec::setcodecforlocale (Qtextcodec::codecforname ("GBK"));
    QTEXTCODEC::SETCODECFORTR (Qtextcodec::codecforname ("GBK"));
    Widget W;
    W.show ();

    return a.exec ();
}
Well, the interface for this case is that I dragged it out of QT designer, so there's no part of the code. Please use the following renderings to view the source code.
Let's show you the effect diagram on the run:



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.