sashoalm
sashoalm

Reputation: 79487

Programmatically edit the contents of a QPlainTextEdit

How can I programmatically edit the contents of a QPlainTextEdit?

For example, I might want to implement a "Find and Replace", or remove a particular line of text, or insert some text.

The trivial approach would be to reload the contents entirely:

QString text = ui->plainTextEdit->toPlainText();
... // Now edit text.
ui->plainTextEdit->setPlainText(text);

However, this seems wasteful, and we will also lose any formatting added via QPlainTextEdit::appendHtml().

Another approach is outlined in Removing last line from QTextEdit - they simulate the user editing the text. The answer is for QTextEdit, but I think it would work for QPlainTextEdit, as well:

ui->textEdit_2->setFocus();
QTextCursor storeCursorPos = ui->textEdit_2->textCursor();
ui->textEdit_2->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
ui->textEdit_2->moveCursor(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
ui->textEdit_2->moveCursor(QTextCursor::End, QTextCursor::KeepAnchor);
ui->textEdit_2->textCursor().removeSelectedText();
ui->textEdit_2->textCursor().deletePreviousChar();
ui->textEdit_2->setTextCursor(storeCursorPos);

Which approach should I use to edit the contents? Does the second one have any advantages?

Edit: Is it even a valid approach, or just a hack?

Upvotes: 0

Views: 1096

Answers (1)

Googie
Googie

Reputation: 6017

QPlainTextEdit documentation stands:

Text can be inserted using the QTextCursor class or using the convenience functions insertPlainText(), appendPlainText() or paste().

So it's a correct way to edit with QTextCursor.

Upvotes: 1

Related Questions