QTextEdit and custom paint event
-
I have the following code snippet in a TextEdit paint event.
@
void TextEdit::paintEvent(QPaintEvent *e)
{
QPainter painter(viewport());QAbstractTextDocumentLayout::Selection selection; selection.cursor = textCursor(); selection.format = currentCharFormat(); QAbstractTextDocumentLayout::PaintContext ctx; ctx.cursorPosition = textCursor().position(); ctx.selections.append(selection); document()->documentLayout()->draw(&painter,ctx);
}
@There are two problems I am looking to fix. The first problem is when I select text you do not see it as select. Second, the cursor is drawn but does not blink. Any suggestions?
-
I assume this isn't a QTextEdit subclass, right?
(If not, why isn't this a qtextedit? it looks very much like one ;)In QTextEdit the cursor blinking is done by a timer (see QTextControlPrivate::setBlinkingCursorEnabled) which calls update() on the right rectangle (see QTextControlPrivate::repaintCursor); you might have to do this by yourself if this isn't a QTextEdit.
For the selections, you need to give them a background color, currentCharFormat() will be "black on white" so basically it doesn't look different from when it's not selected. Looking at QTextControl::getPaintContext I'd say you need to do something like
@
QPalette::ColorGroup cg = d->hasFocus ? QPalette::Active : QPalette::Inactive;
selection.format.setBackground(ctx.palette.brush(cg, QPalette::Highlight));
selection.format.setForeground(ctx.palette.brush(cg, QPalette::HighlightedText));
@ -
Yes this is a subclass of QTextEdit. I do see that I have to do all the blinky cursor stuff myself. QPlainTextEdit has a really nice convenience function called getPaintContext that handles the state of the cursor for you, wish they had the same call in QTextEdit. oh well.