PDA

View Full Version : QTextEdit find all



niol1000
6th January 2010, 09:16
Hi all,

I'm trying to find a way find all occurrences of a specified string in a QTexedit document. The QTextedit::find() function only selects the first occurrence. For example consider the following text:

"the dog the cat",

If i search for string "the" I want to highlight both "the". I also tried using the QTextDocument::find() function and QRegexp with no luck.

Anyone here that have any suggestion to solve my problem.

/Nick

niol1000
11th January 2010, 15:19
I'm really stuck with this problem, do the lack of replys means that's there is no easy way to do it or that its so simple so nobody reply for that reason :)

boudie
11th January 2010, 20:03
I think you have to call find() from the beginning of the document until it returns false.
At every hit you can insert html-code to highlight the search string.

wysota
11th January 2010, 23:25
At every hit you can insert html-code to highlight the search string.

It's better to use QTextEdit::setExtraSelections() for that.

niol1000
12th January 2010, 14:01
Thank you for your reply's, I will check both your suggestions....

niol1000
12th January 2010, 16:45
Thanks alot for pointing me to the solution for my problem, here is the code I use, it somewhat slow but its good enough for me.



void TextWidget::search(QString& str, bool matchCase)
{
QList<QTextEdit::ExtraSelection> extraSelections;

if(!ui->textEdit->isReadOnly())
{
ui->textEdit->moveCursor(QTextCursor::Start);
QColor color = QColor(Qt::gray).lighter(130);

while(ui->textEdit->find(str))
{
QTextEdit::ExtraSelection extra;
extra.format.setBackground(color);

extra.cursor = ui->textEdit->textCursor();
extraSelections.append(extra);
}
}

ui->textEdit->setExtraSelections(extraSelections);
}