Qt QProcess Tutorial

When I use Qt, I try to used or start external program from Qt. After searching in qassistant, I get a class QProcess to used or start external program from Qt. So, I try to create Qt QProcess tutorial in my post. This my Qt QProcess tutorial is basic tutorial to use QProcess in Qt. I try to create a Qt QProcess tutorial to call another command or external program from Qt and display success or error message if that program have.

Before we can use QProcess class, we must include <QProcess> in our header program. I create this Qt QProcess tutorial to running under linux. I use bash script to process string from user typed. If program called have success or error message, this Qt program will print that string with function readAllStandardOutput (if program success) or readAllStandardError (if program error).

This is a my simple script function in Qt QProcess tutorial to use QProcess and print output if program success or fail.

void tesQProcess::on_btnProcess_clicked()
{
    QString str_command;

    /* clear text report */
    ui->txtReport->clear();

    /* create string command and argument */
    str_command = ui->lineeCommand->text();

    /* create QProcess object */
    proc= new QProcess();
    proc->start("/bin/bash", QStringList() << "-c" << QString(str_command));

    /* show output */
    connect(proc, SIGNAL(readyReadStandardOutput()),this, SLOT(rightMessage()) );
    connect(proc, SIGNAL(readyReadStandardError()), this, SLOT(wrongMessage()) );
}

// show right message
void tesQProcess::rightMessage()
{
    QByteArray strdata = proc->readAllStandardOutput();
    ui->txtReport->setTextColor(Qt::black);
    ui->txtReport->append(strdata);
}

// show wrong message
void tesQProcess::wrongMessage()
{
    QByteArray strdata = proc->readAllStandardError();
    ui->txtReport->setTextColor(Qt::red);
    ui->txtReport->append(strdata);
}

This Qt QProcess tutorial will print text with color black (if success) and red if fail/error. This is output from this code :

If you want to running this program under windows, you must modified this code proc->start(). Because, I communicate user typed command with bash script, and windows dont have bash. This is a simple Qt QProcess tutorial. So, you can know how to use QProcess in your application. You can read the complete QProcess class in Qt Documentation.  You can download all this code in this location.

5 Comments

Leave a Reply to Prashant Cancel reply

Your email address will not be published. Required fields are marked *