1

I have a QTextEdit and I am trying to insert text to top of that using following code

void HuggleLog::InsertText(QString text)
{
    ui->textEdit->cursorForPosition(QPoint(0,0));
    ui->textEdit->insertPlainText(text);
}

I am trying to move the cursor to beginning of text area so that text get inserted infront of current text, but it doesn't work. What is a correct way? There is append() method but no prepend.

arrowd
  • 33,231
  • 8
  • 79
  • 110
Petr
  • 13,747
  • 20
  • 89
  • 144
  • 1
    Just a trick: `QString newtext = textEdit->toPlainText(); newtext.prepend(text); textEdit->setPlainText(newText);` – vahancho Sep 17 '13 at 13:42
  • @vahancho Sounds cool and in fact I tried that before, but I am afraid this would require far more CPU as it would need to render whole text everytime from scratch. Also it was crashing my app randomly when I needed to insert lot of text (called that function like thousand times within few seconds) – Petr Sep 17 '13 at 14:09
  • @ Peter, yeah. I didn't pretend to say that this solution is the best one. That's why I called it "a trick":) BTW, if you prepend text with other methods, won't it provoke a redraw too - your text will shift right/down anyways? – vahancho Sep 17 '13 at 14:15

2 Answers2

4

What about this:

QString oldText = ui->textEdit->toPlainText(); // or toHtml()
ui->textEdit->setPlainText(text + oldText);    // or setText() or setHtml()
headsvk
  • 2,726
  • 1
  • 19
  • 23
  • This was crashing my app for unknown reasons (when I was doing that many times within short time), but I will try to play with that a bit – Petr Sep 17 '13 at 14:10
  • 'class QTextEdit' has no member named 'text' – Petr Sep 17 '13 at 14:13
  • I figured it is crashing because I insert it using different thread :), so yes, this kind of works, when I replace text() with toPlainText() and setText to setPlainText() – Petr Sep 17 '13 at 14:16
  • Oh sorry, I forgot there's no text() method. Either you have html or plain text. Using plain text could be faster if you don't need formatting. – headsvk Sep 17 '13 at 14:23
2

I believe what you're looking for is http://qt-project.org/doc/qt-5.1/qtwidgets/qtextedit.html#moveCursor with http://qt-project.org/doc/qt-5.1/qtgui/qtextcursor.html#MoveOperation-enum. Should look like:

ui->textEdit->moveCursor(QTextCursor::start, 0);
Aerius
  • 588
  • 5
  • 24