PDA

View Full Version : Pre-processing entered text in QTextDocument



srazi
8th May 2017, 12:21
I want something like the following example:
User start to type in QTextDocument "abc" I want change it to "ABC" and send it to QTextDocument so all other part of QTextDocument API like syntax-highlighting and text layouting should get "ABC" and not "abc".

I didn't find a method about this so I used QTextDocument::contentsChange() signal to detect new added chars and then preprocess them (in this example apply toUpper()) but this is dirty and QAbstractTextDocumentLayout::documentChanged() will be called twice.

Any idea?

Santosh Reddy
8th May 2017, 13:34
I think you are mixing up "Replace All" and "Auto Correction/Formatting" features, better to implement them separately.



I didn't find a method about this so I used QTextDocument::contentsChange() signal...

Method to find and replace: Use toPlainText(), replace the text and then it back setPlainText(). If using this inside a slot connected to contentsChange() signal, take care to blockSignals(true), and blockSignals(false) guard statements while setting the new text to avoid recursion.




MyTextDocument::on_contentsChange()
{
blockSignals(true);
QString text = toPlainText();
// find and replace in text
setPlainText(text);
blockSignals(false);
}

srazi
9th May 2017, 00:19
Thanks for your reply. But as I want do this pre-processing on the fly, using "setPlainText(text)" seems to be slow on large documents.