PDA

View Full Version : Higliting matching brackets in QPlainTextEdit



Nebelig
27th April 2011, 18:55
I have implemented the method of highlighting matching brackets in my class



void CodeEditor::cursorPositionChanged()
{
if (!bracketBeginCursor.isNull() || !bracketEndCursor.isNull()) {
bracketBeginCursor.setCharFormat(QTextCharFormat() );
bracketEndCursor.setCharFormat(QTextCharFormat());
bracketBeginCursor = bracketEndCursor = QTextCursor();
}

QTextCursor cursor = textCursor();

int position = cursor.position();

if ((!cursor.atBlockEnd() && doc->characterAt(position) == '(') ||
(!cursor.atBlockStart() && doc->characterAt(position - 1) == ')')) {

bool forward = doc->characterAt(position) == '(';

QTextCursor::MoveOperation move;

QChar c, begin, end;

if (forward) { //bool forward =
position++;
move = QTextCursor::NextCharacter;
begin = '(';
end = ')';

} else {
position -= 2;
move = QTextCursor::PreviousCharacter;
begin = ')';
end = '(';
}

bracketBeginCursor = QTextCursor(cursor);
bracketBeginCursor.movePosition(move, QTextCursor::KeepAnchor);

QTextCharFormat format = bracketMismatchFormat;

int braceDepth = 1;

while (!(c = doc->characterAt(position)).isNull()) {
if (c == begin) {
braceDepth++;
} else if (c == end) {
braceDepth--;

if (!braceDepth) {
bracketEndCursor = QTextCursor(doc);
bracketEndCursor.setPosition(position);
bracketEndCursor.movePosition(QTextCursor::NextCha racter, QTextCursor::KeepAnchor);
bracketEndCursor.setCharFormat(bracketMatchFormat) ;

format = bracketMatchFormat;

break;
}
}
forward ? position++ : position--;
}
bracketBeginCursor.setCharFormat(format);
}
}


everything works fine, but if the bracket is highlighted and is the first in a block, then the text is placed to the left of it will have the same QTextCharFormat...

Perhaps there is a link with

QTextCharFormat QTextCursor::charFormat () const
Returns the format of the character immediately before the cursor position().
If the cursor is positioned at the beginning of a text block that is not empty then the format of the character immediately after the cursor is returned.

Thanks for any advice.

msr
2nd May 2013, 00:07
(this is an old topic I know)

One issue of this code is that it changes the undo/redo history of the qplaintextedit. Is there any way to disable the undo/redo while changing the qtextcharformat so it isn't added to the undo stack? Thanks

wysota
2nd May 2013, 01:17
The method described in this thread is outdated. Use QPlainTextEdit::setExtraSelections() instead.