Reputation: 7064
void QTextDocument::contentsChange(int position, int charsRemoved, int charsAdded) [signal]
This signal is emitted whenever the document's content changes; for example, when text is inserted or deleted, or when formatting is applied.
User can click cut/press delete/backspace or any other way and will remove text. Problem is this signal emitted after text is removed. So I don't know which text was deleted.Now position and charsRemoved are of no use.
I want to find out deleted text of QPlainTextEdit. Is there any way to achieve this?
Upvotes: 2
Views: 1042
Reputation: 1973
The trick with calling undo
and redo
suggested by Googie is nice, to make it even more efficient one can use a QTextCursor
to extract the text instead of calling toPlainText
:
void TextEdit::slotCheckRange(int pos, int removed, int added){
if(removed > 0){
undo();
QTextCursor c(textCursor());
c.setPosition(pos);
c.setPosition(pos + removed, QTextCursor::KeepAnchor);
qDebug() << "Removed: " << removed << " (" << c.selectedText() << ")";
redo();
}
if(added > 0){
QTextCursor c(textCursor());
c.setPosition(pos);
c.setPosition(pos + added, QTextCursor::KeepAnchor);
qDebug() << "Added: " << added << " (" << c.selectedText() << ")";
}
}
Upvotes: 2
Reputation: 6017
I see 2 possible solutions:
Store the contents of the document after every contents change, so in every next change you will have access to the previous contents and you will be able to extract the value using position and charsRemoved.
Pros: It's isolated mechanism and will not interfere with any other signals or slots.
Cons: It implies significant memory and CPU footprint (every text change causes full string copy).
(a better one in my opinion) In the slot function implementation use the undo()
and redo()
methods of the QPlainTextEdit
to restore previous contents for the time of querying charsRemoved. Note, that calling undo()
and redo()
will not trigger the contentsChange()
signal (I just tested it), so it's as simple as that.
Pros: Doesn't cause additional memory footprint. Not sure about the CPU footprint, but I think it's also better in that case.
Cons: This will only work with Undo/Redo mechanism enabled (which it is by default) and it also might affect any undo/redo code that you use or override (usually it's not the case).
To be clear, a sample code snipped for solution 2:
void MainWindow::textChanged(int pos, int rem, int add)
{
ui->plainTextEdit->undo();
qDebug() << ui->plainTextEdit->document()->toPlainText().mid(pos, rem); // <- text removed
ui->plainTextEdit->redo();
qDebug() << ui->plainTextEdit->document()->toPlainText().mid(pos, add); // <- text added
}
Upvotes: 1