views:

413

answers:

2

I have often wanted to use QTextEdit as a quick means of displaying what is being written to a stream. That is, rather than writing to QTextStream out(stdout), I want to do something like:

 QTextEdit qte; 
 QTextStream out(qte);  

I could do something similar if I emit a signal after writing to a QTextStream attached to a QString.
The problem is that I want the interface to be the same as it would if I were streaming to stdout etc.:

out << some data << endl;

Any ideas on how I might accomplish this?

Thanks in advance.

+2  A: 

You can subclass the QTextEdit and implement the << operator to give it the behaviour you want ; something like:

class TextEdit : public QTextEdit {
    .../...
    TextEdit & operator<< (QString const &str) {
        append(str);

        return *this;
    }
};
gregseth
Nice. I also tried to do it that way but I've spent whole day trying to make operator chaining work with no effect. Thanks
Moomin
However, it is still not possible to use `QTextStream` options (e.g. output formatting)
Moomin
+1  A: 

You can create a QIODevice that outputs to QTextEdit.

class TextEditIoDevice : public QIODevice 
{
    Q_OBJECT

public:
    TextEditIoDevice(QTextEdit *const textEdit, QObject *const parent) 
        : QIODevice(parent)
        , textEdit(textEdit)
    {
        open(QIODevice::WriteOnly|QIODevice::Text);
    }

    //...

protected:
    qint64 readData(char *data, qint64 maxSize) { return 0; }
    qint64 writeData(const char *data, qint64 maxSize)
    {
        if(textEdit)
        {
            textEdit->append(data);
        }
        return maxSize;
    }

private:
    QPointer<QTextEdit> textEdit;
};


// In some dialogs constructor
QTextStream  ss(new TextEditIoDevice(*ui.textEdit, this));
ss <<  "Print formatted text " <<hex << 12 ;
// ...
TimW