PDA

View Full Version : QPlainTextEdit highlight word



ArkKup
4th March 2013, 13:57
Hi,

In my texteditor application I'd like to highlight all occurrence of a word under cursor. The problem is that it works for all lines except highlighted line.


void CodeEditor::test()
{
highlightCurrentLine(); //function based on CodeEditor example
highlightCurrentWord("bar");
}

void CodeEditor::highlightCurrentWord(QString curWord)
{
QTextCharFormat fmt;
fmt.setBackground(Qt::red);
fmt.setForeground(Qt::black);
//...
QTextCursor cursor = QTextCursor(block);
cursor.select(QTextCursor::WordUnderCursor);
//...
cursor.setPosition(begin, QTextCursor::MoveAnchor);
cursor.setPosition(end, QTextCursor::KeepAnchor);
cursor.mergeCharFormat(fmt); //I did try also cursor.setCharFormat(fmt);
//...


So for example if I have three lines

foo xyz bar

bar edddd

abc bar

let's say line 1 is cursor current line and therefore is highlighted. I want to highlight 'bar' word it will be highlighted in lines 2, 3 but not in line 1 cause of line highlight present.

Anyone know how to solve this issue ? somehow merge formating ?

Thanks in advance!

wysota
4th March 2013, 16:23
void CodeEditor::highlightCurrentLine()
{
QList<QTextEdit::ExtraSelection> extraSelections;

if (!isReadOnly()) {
QTextEdit::ExtraSelection selection;

QColor lineColor = QColor(Qt::yellow).lighter(160);

selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidt hSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();
extraSelections.append(selection);
}

// BEGIN: added
QTextCursor cursor = textCursor();
cursor.select(QTextCursor::WordUnderCursor);
QTextEdit::ExtraSelection currentWord;
QColor redColor = Qt::red;
currentWord.format.setBackground(redColor);
currentWord.cursor = cursor;
extraSelections.append(currentWord);
// END: added

setExtraSelections(extraSelections);
}