Need help on QTextEdit
Hi all,
In my texteditor, I added find&replace option. The logic is working fine but I need to highlight ( or select ) the text that is found or replaced. It will be good if text found or getting replaced has some background color or highlighted.
Code:
- void MainWindow::replaceText()
- {
- {
- textEdit->insertPlainText(replaceLineEdit->text());
- }
- }
Plz help me regarding this..
Thanks,
Haney.
Edit: Please use @ tags around code sections. There is a button for it at the top of the editor too; Andre
8 replies
To cite QTextEdit::textCursor() [doc.qt.nokia.com] API docs:
Returns a copy of the QTextCursor that represents the currently visible cursor. Note that changes on the returned cursor do not affect QTextEdit’s cursor; use setTextCursor() to update the visible cursor.
Change your code to:
- void MainWindow::replaceText()
- {
- {
- textEdit->insertPlainText(replaceLineEdit->text());
- textEdit->setTextCursor(c);
- }
- }
Hi,
Thanks for the reply..
I changed the code and it is working for only the first time the word is replaced. Next time when I press replace button again it is replacing the word but that word is not visible. Third time when I press replace button third occurrence is not visible but now second occurrence is visible and it goes on till last occurrence of the word.
Plz help me if can get the word selected every time when it is replaced.
Thanks,
Haney.
Perhaps you can (ab)use QSyntaxHighlighter in some way? Just an idea, I never tried this myself. If not, it might still provide the inspiration you need.
- {
- textEdit->insertPlainText(replaceLineEdit->text());
- c.setCharFormat(format);
- }
I tried this to set some background color in order to highlight the replaced word. But after textEdit gains back focus the highlighted part should come to normal and that is not happening.. I tried clearBackground() and it dint work for me..
Please share any other ideas to highlight the replaced word similar to implementation of find/replace option in QtCreator IDE.
QTextEdit::ExtraSelection could be a solution for you. Have a look at my wiki article on spell checking with hunspell, it shows you how to use it.
Thanks for ur reply.. I tried the following code in my findNext() slot but it did not work.
- if(!textEdit->isReadOnly())
- {
- extra.format.setBackground(color);
- extra.cursor = textEdit->textCursor();
- extraSelections.append(extra);
- }
- textEdit->setExtraSelections(extraSelections);
Can you plz share a piece of code that sets some background color of word and when I close my find/replace dialog that color should disappear.
Thanks,
Haney.
You must log in to post a reply. Not a member yet? Register here!


