开发者

Streaming to QTextEdit via QTextStream

开发者 https://www.devze.com 2022-12-21 06:47 出处:网络
I have often wanted to use QTextEdit as a quick means of displaying what is being written to a stream.That 开发者_如何学Pythonis, rather than writing to QTextStream out(stdout), I want

I have often wanted to use QTextEdit as a quick means of displaying what is being written to a stream. That 开发者_如何学Pythonis, 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.


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 ;
// ...


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;
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消