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 tostdout
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;
}
};
精彩评论