def paintEvent(self, event): contents_y = self.edit.verticalScrollBar().value() page_bottom = contents_y + self.edit.viewport().height() font_metrics = self.fontMetrics() current_block = self.edit.document().findBlock( self.edit.textCursor().position()) painter = QPainter(self) first_line = self.edit.firstVisibleBlock().firstLineNumber() # print(self.highest_line.data()) line_count = 0 # Iterate over all text blocks in the document. block = self.edit.document().begin() while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.document().documentLayout().blockBoundingRect( block).topLeft() # Check if the position of the block is out side of the visible # area. if position.y() > page_bottom: break # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). font = QFont() font.setPointSize(self.edit.font().pointSize()) font.setWordSpacing(20) painter.setFont(font) if line_count == 1: painter.drawText( self.width() - font_metrics.width(str(line_count + first_line)) - 3, 1 + 17 * line_count, str(first_line + line_count)) else: painter.drawText( self.width() - font_metrics.width(str(line_count + first_line)) - 3, 1 + 17 * line_count + (self.edit.font().pointSize() - 10) * line_count * 2, str(first_line + line_count)) #print(self.width() - font_metrics.width(str(line_count)) - 3 , " " , round(position.y()) - contents_y + font_metrics.ascent(), str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) block = block.next() self.highest_line = line_count painter.end() QWidget.paintEvent(self, event)