I've got this simple code in the paintEvent of my QTextEdit which draws a grey box under the currently selected QTextBlock:
def paintEvent(self, ev):
painter = QPainter()
painter.begin(self.viewport())
currentPos = self.textCursor().position()
block = self.document().findBlock(currentPos)
rect = self.document().documentLayout().blockBoundingRect(block)
margin = self.document().documentMargin()
rect.setTopLeft(QPoint(int(rect.topLeft().x()-margin), int(rect.topLeft().y()-margin)))
rect.setBottomRight(QPoint(int(rect.bottomRight().x()+margin), int(rect.bottomRight().y())))
painter.fillRect(rect, QBrush(QColor(10, 10, 10,20)))
if self._last_selected_block and (self._last_selected_block != block):
lastrect = self.document().documentLayout().blockBoundingRect(self._last_selected_block) #clean up artifacts
painter.eraseRect(lastrect)
painter.fillRect(self.contentsRect(), QBrush(QColor(123, 111, 145, 80))) #background color
painter.end()
self._last_selected_block = block
super().paintEvent(ev)
(Note, the "clean up artifacts" line erases anything drawn in the region of the previously selected QTextBlock, since a thin grey line would remain under the last block if text was drawn in it. Might be related.)
However, when the cursor is moved via clicking on another line, this happens:
The next rectangle is only partially drawn, around the character which the cursor was moved to, and the previous one is not erased. eraseRect() doesn't seem to be able to remove this artifact. When typing is continued or a newline is made, everything goes back to normal (this issue never occurs when changing lines via making a newline). I've confirmed that paintEvent() is called when the cursor moves, and the width of the rectangles to be drawn never changes. What's happening here?