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) 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). # painter.drawText(self.width() - len(str(line_count)) * font_metrics.averageCharWidth() - 5, 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)
def paintEvent(self, ev): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.TextAntialiasing) f = painter.font() f.setBold(True) f.setPixelSize(self.height() - 1) painter.setFont(f) painter.setPen(QColor('red' if self.is_enabled else 'green')) painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, 'Z') painter.end()