Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting QProcess and reading its output one line at a time

Tags:

c++

qt

What would be the preferred way in Qt of reading a child process output one line at a time as it appears?

I tried connecting QProcess signal readyReadStandardOutput to the function that calls QProcess method readLine.

like image 494
Michael Avatar asked Oct 29 '13 21:10

Michael


1 Answers

The preferred way is the asynchronous way, using signals emitted by QIODevice. Your approach is correct. Make sure that you read all available lines within your slot:

process->setReadChannel(QProcess::StandardOutput);
while (process->canReadLine()) {
   QString line = QString::fromLocal8bit(process->readLine());
   ...
}

Also remember that once you read something, it's not available to be read again. QIODevice's signals need to be used with care - you can't connect an arbitrary number of consumers to the readyRead signal and perform the reading in each of them. It won't work the way you might have expected it to. If the first reader reads all of the data, the subsequent ones won't be able to read it again.

like image 189
Kuba hasn't forgotten Monica Avatar answered Oct 30 '22 22:10

Kuba hasn't forgotten Monica