4

I am a newbie in qt development and i want to transfer the output of QProcess to a textBrowser in real time. I started by executing a simple echo command,but the output of the program is not getting displayed. What am i doing wrong????

QProcess p;
p.start("echo hye");
QByteArray byteArray = p.readAllStandardOutput();
    QStringList strLines = QString(byteArray).split("\n");
    QString line= p.readAllStandardOutput();
    if(p.state()==QProcess::NotRunning)
        ui->textBrowser->append("not running");
    foreach (QString line, strLines){
    ui->textBrowser->append(line);}

P.S. I am on a linux machine.

EDIT: I am still not able to get the output in a textBrowser .

I changed the Qprocess parameters and tried both waitForStarted() and waitForReadyRead() so that the process starts in time and the results are available.

I added waitForFinished() so that the process does not terminate when it goes out of scope.

QProcess p;
    p.start("echo", QStringList() << "hye");
    p.waitForStarted();
    QByteArray byteArray = p.readAllStandardOutput();
    QStringList strLines = QString(byteArray).split("\n");
    QString line= p.readAllStandardOutput();
    if(p.state()==QProcess::NotRunning)
        ui->textBrowser->append("not running");
    ui->textBrowser->append(line);
    p.waitForFinished();
Tanmay J Shetty
  • 197
  • 2
  • 3
  • 9

1 Answers1

9

to read standard output you need to either call waitForReadyRead() before reading stardard output , or you need to connect Qprocess's signal readyReadStandardOutput() to your slot and read standard output from slot.

also make sure that your QProcess is not on stack.

I tried following code works fine.

EDIT:

MyProcess::MyProcess(QObject *parent) :
    QObject(parent)
{
    QString program = "echo";
    QStringList arguments;
    arguments << "Hello";
    mProcess.start(program,arguments);
    connect(&mProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()));
    connect(&mProcess,SIGNAL(readyReadStandardError()),this,SLOT(readyReadStandardError()));
}

void MyProcess::readyReadStandardOutput(){
    qDebug()<< mProcess.readAllStandardOutput();
}

void MyProcess::readyReadStandardError(){
    qDebug() << mProcess.readAllStandardError();
}
Kunal
  • 3,475
  • 21
  • 14
  • I would like to display the results in a textBrowser,but this code displays results in qt's terminal itself. – Tanmay J Shetty Apr 11 '12 at 23:54
  • well, you can use ui->textBrowser->append instead of qDebug() – Kunal Apr 12 '12 at 00:37
  • 1
    See https://sites.google.com/site/marcsturmspages/qt/qt-workaround-for-the-leaky-qprocess-output-channel for the buffering issue and its workaround. – Answeror Jun 21 '13 at 01:33
  • Thanks for reminding on waitForReadyRead()! For my app it was sufficient and using this doesn't require to subclass from QProcess. – Valentin H Aug 02 '15 at 15:26