Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append text to QPlainTextEdit without adding newline, and keep scroll at the bottom?

I need to append text to QPlainTextEdit without adding a newline to the text, but both methods appendPlainText() and appendHtml() adds actually new paragraph.

I can do that manually with QTextCursor:

QTextCursor text_cursor = QTextCursor(my_plain_text_edit->document());
text_cursor.movePosition(QTextCursor::End);

text_cursor.insertText("string to append. ");

That works, but I also need to keep scroll at bottom if it was at bottom before append.

I tried to copy logic from Qt's sources, but I stuck on it, because there actually QPlainTextEditPrivate class is used, and I can't find the way to do the same without it: say, I don't see method verticalOffset() in QPlainTextEdit.

Actually, these sources contain many weird (at the first look, at least) things, and I have no idea how to implement this.

Here's the source code of append(): http://code.qt.io/cgit/qt/qt.git/tree/src/gui/widgets/qplaintextedit.cpp#n2763

like image 323
Dmitry Frank Avatar asked Nov 26 '12 06:11

Dmitry Frank


2 Answers

I'll just quote what I found here:

http://www.jcjc-dev.com/2013/03/qt-48-appending-text-to-qtextedit.html


We just need to move the cursor to the end of the contents in the QTextEdit and use insertPlainText. In my code, it looks like this:

myTextEdit->moveCursor (QTextCursor::End);
myTextEdit->insertPlainText (myString);
myTextEdit->moveCursor (QTextCursor::End);

As simple as that. If your application needs to keep the cursor where it was before appending the text, you can use the QTextCursor::position() and QTextCursor::setPosition() methods, or

just copying the cursor before modifying its position [QTextCursor QTextEdit::textCursor()] and then setting that as the cursor [void QTextEdit::setTextCursor(const QTextCursor & cursor)].

Here’s an example:

QTextCursor prev_cursor = myTextEdit->textCursor();
myTextEdit->moveCursor (QTextCursor::End);
myTextEdit->insertPlainText (myString);
myTextEdit->setTextCursor (&prev_cursor);
like image 117
david Avatar answered Nov 12 '22 01:11

david


The current Answer was not an option for me. It was much simplier to add html with no new lines with the following method.

//logs is a QPlainTextEdit object
ui.logs->moveCursor(QTextCursor::End);
ui.logs->textCursor().insertHtml(out);
ui.logs->moveCursor(QTextCursor::End);
like image 10
andre Avatar answered Nov 12 '22 01:11

andre