Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: is there a way to send a signal when a QProcess writes a line to stdout

Tags:

qt

qt4

I've found similar questions but never the exact answer. I have Qt program that starts a QProcess and writes the output to a QTextEdit box, so far so good. But it only does so when the program has ended. if possible I'd like the programs stdout to be printed in real-ish time. In an ideal world there would be some sort of signal that QProcess emits when there is a line ready to read, if its not possible with QProcess is it possible at all? Also Ideally you could still use the rest of the program while the process is running.

Heres some of the code i have so far, very simple, it just emits the first line of the QProcess stdout to a QTextEdit

...
extProcess::extProcess(QObject *parent) :
    QObject(parent)
    extProcess::extProcess(QObject *parent) :
    QObject(parent)
{
    proc = new QProcess(this); //initialize proc
    arguments << "-v";
    connect(proc, SIGNAL(readyRead()), this, SLOT(logReady()));

}

void extProcess::startProcess()
{
    emit clearLog();
    emit outLog("--Process started--");
    proc->start("/Users/jonathan/Desktop/testgg");
}

void extProcess::logReady()
{
       emit outLog(proc->readLine());
}
...

This is al alternate version I tried, this will show the entire QProcess output but still only shows it when the program finishes.

    ...
    extProcess::extProcess(QObject *parent) :
    QObject(parent)

{
    proc = new QProcess(this); //initialize proc
    proc->setProcessChannelMode(QProcess::SeparateChannels);
    arguments << "-v";
    connect(proc, SIGNAL(readyReadStandardOutput()), this, SLOT(logReady()));

}


void extProcess::logReady()
{

       while(proc->bytesAvailable()){
               emit outLog(proc->readLine());
       }
}



void extProcess::startProcess()
{
    emit clearLog();
    emit outLog("--Process started--");
    proc->start("/Users/jonathan/Desktop/testgg");
}



void extProcess::killProcess()
{
    proc->terminate();
    emit clearLog();
    emit outLog("--Process Terminated--");
}
....

Thanks

like image 725
jonathan topf Avatar asked Dec 21 '22 12:12

jonathan topf


1 Answers

I use readAllStandardOutput() for this exact purpose and it works for me.

However I did note that it won't recieve any standard output until the process actually flushes its output buffer ("\n" may not automagically do this, at least not in my entirely platform specific Windows experience).

Depending on how the child process writes its output (either a C app or a C++ app), it needs to call fflush(stdout); or end lines with std::endl; respectively.

like image 116
badgerr Avatar answered Dec 28 '22 09:12

badgerr