PDA

View Full Version : Display content wirtten to STL::ostream dynamically



kai
7th January 2009, 06:30
Hi,

My application writes to an C++ STL output stream (ostream) during the execution of the program. I would like to display the whatever written to the ostream immediately to an widget (such as QDockWidget).

I have been looking through document and examples related to QTextStream/QTextEdit/QDataStream, and still can't figure out how to do this. For example, for QTextStream, it only takes FILE as an argument but not an ostream. For QTextEdit, it doesn't seem it can do this either.

Any guide or even an example would be greatly appreciated.

Regards,
Kai

kai
8th January 2009, 00:12
I found the following link in this forum posted a few years ago. The solution described in that link works! Thanks for those whose posted that link.

http://www.qtforum.org/article/678/Redirecting-coutcerr-to-qDebug.html

kai
8th January 2009, 00:49
There is another problem though. QTextEdit seems to display the content from ostream only when ostream is done taking input. I tried ostream::flush(), it doesn't help. Following is the code segment that uses the QTextEdit and ostream redirection. Any idea why QTextEdit is slow to display?

//------ .cpp file

DeOutputWindow::DeOutputWindow () : QDockWidget("Output")
{

_outputTextEditor = new QTextEdit();
_outputTextEditor->setReadOnly(false);
_outputTextEditor->setTextInteractionFlags(Qt::NoTextInteraction);
_outputStream = new DeOutputStream(std::cout, _outputTextEditor);
setWidget(_outputTextEditor);
}

//------- .hpp file

class DeOutputWindow : public QDockWidget
{
Q_OBJECT
public:
/// Constructor
DeOutputWindow ();
/// Destructor
virtual ~DeOutputWindow ();

private:
QTextEdit* _outputTextEditor;
DeOutputStream* _outputStream;
};

/// A class that redirect output to an std::ostream to a QTextEdit

class DeOutputStream : public std::basic_streambuf<char>
{
public:
/** Constructor
* @param out
* The ostream whose content will be redirected to text edit
* @param textEditor
* The window that will display the text written to ostream
*/
DeOutputStream (std::ostream& out, QTextEdit* textEditor);
/// Destructor
~DeOutputStream ();

protected:
/// Override method that construct the text string and overflow
virtual int_type overflow (std::basic_streambuf<char>::int_type v);

/// Override method that take in the text character
virtual std::streamsize xsputn (const char* p, std::streamsize n);

private:
std::ostream& _out; // ostream whose content will be redirected to text edit
std::streambuf* _oldBuffer; // Old buffer of the ostream
QTextEdit* _textEditor; // Displaying text editor
std::string _text; // Text to be displayed
};