Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming to QTextEdit via QTextStream

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.

like image 966
Moomin Avatar asked Dec 29 '22 00:12

Moomin


2 Answers

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 ;
// ...
like image 156
TimW Avatar answered Jan 08 '23 10:01

TimW


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;
    }
};
like image 39
gregseth Avatar answered Jan 08 '23 12:01

gregseth