[Qt-interest] How to capture stdout and redirect it to the gui?

K. Frank kfrank29.c at gmail.com
Thu Jan 27 04:03:28 CET 2011


Hello Bob!

On Wed, Jan 26, 2011 at 7:55 PM, Bob Hood <bhood2 at comcast.net> wrote:
> On 1/26/2011 3:42 PM, K. Frank wrote:
>> I would like to "capture" stdout and redirect it to a logging
>> window, for example, a QTextEdit.
>> ...
>> Would someone know of a solution or have suggestions about
>> things to try?
>>
>
> Here's an excerpt of code I use to capture and process the output of a
> sub-process.  This should do what you're asking.  Note that I also merge the
> channels, so stdout and stderr come in through stdout:

Thanks for this.

>    ...
>    process = new QProcess();
>    process->setProcessChannelMode(QProcess::MergedChannels);
>
>    if(working_path.size())
>        process->setWorkingDirectory(working_path);
>
>    connect(process, SIGNAL(finished(int)), this,
> SLOT(slot_process_finished(int)));
>
>    if(capture)
>    {
>        capture_elapsed = std::numeric_limits<int>::max();
>        capture_timer.start();
>        capture_called = false;
>        connect(process, SIGNAL(readyReadStandardOutput()), this,
> SLOT(slot_read_output()));
>    }
>
>    process->start(command, args);
>    ...
>
> So, in your method to read the output (e.g., "slot_read_output" above), you
> just read what's currently available and then post it to your widget.

I haven't used QProcess before, so let me ask some simple
questions.

In my case, I don't have a separate process; instead,  I call an
in-process library (that writes to stdout, and that I would prefer
not to modify).  Is it possible for an already running Qt gui process
to get a handle to itself and read its own stdout?  How would I
go about doing this?  Or does your method only work when the
"main" process creates a second child process?

Thanks for your help.


K. Frank



More information about the Qt-interest-old mailing list