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?
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()andredo()methods of theQPlainTextEditto restore previous contents for the time of querying charsRemoved. Note, that callingundo()andredo()will not trigger thecontentsChange()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: