Streaming to QTextEdit via QTextStream

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

QTextEdit qte; QTextStream out(qte); 

I could do something like this if I emitted a signal after writing to a QTextStream attached to a QString.
The problem is that I want the interface to be the same as if I were streaming in stdout , etc .:

 out << some data << endl; 

Any ideas on how I can do this?

Thanks in advance.

+4
source share
2 answers

You can subclass QTextEdit and implement the << operator to give it the behavior you want; sort of:

 class TextEdit : public QTextEdit { .../... TextEdit & operator<< (QString const &str) { append(str); return *this; } }; 
+2
source

You can create a QIODevice that displays in a 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 ; // ... 
+7
source

Source: https://habr.com/ru/post/1302662/


All Articles