[Interest] QTextEdit line number paint event

Sensei senseiwa at gmail.com
Tue Jun 4 17:06:00 CEST 2013

Dear all,

I modified the QPlainTextEdit example that draws line numbers to suit my 
taste. What I'd want is simple: display the line number in red if it's 
the current line, gray otherwise.

It turns out, the paint event seems to be not in sync with the current 
status, leaving unmarked lines or having double red lines, as if it 
didn't re-paint them. All I added is a naive if, as you can see below.

Any hints?

// Draw the line numbers widget
void Editor::lineNumberAreaPaintEvent(QPaintEvent *event)
     // Create the main painter
     QPainter painter(lines_);

     // Create the rectangle
     painter.fillRect(event->rect(), QColor(241, 241, 241));

     // Get the visible blocks of text
     QTextBlock block = firstVisibleBlock();
     int blockNumber  = block.blockNumber();
     int top          = (int) 
     int bottom       = top + (int) blockBoundingRect(block).height();

     // Loop for all visible blocks
     while (block.isValid() && top <= event->rect().bottom())
         // If we can paint it
         if (block.isVisible() && bottom >= event->rect().top())
             // Line number
             QString number = QString::number(blockNumber + 1);
             // Set the style
             if (blockNumber != textCursor().blockNumber())
             // Draw the text
             painter.drawText(0, top, lines_->width(), 
fontMetrics().height(), Qt::AlignRight, number);
         // Go to next block of text
         block  = block.next();
         top    = bottom;
         bottom = top + (int) blockBoundingRect(block).height();

More information about the Interest mailing list