Edit添加行號其實是一個控件重繪的過程。python
須要在Edit中重繪一個矩形區域,而後把行號「畫」在這個矩形區域上。git
首先,須要定義一個行號欄類:函數
class NumberBar(QtGui.QWidget): def __init__(self, editor): QtGui.QWidget.__init__(self, editor) self.codeEditor = editor #get行號值 def getWidth(self): digits = 1 try: if ui.ui2isOpen: blockNumber = ui2.verticalScrollBar1.value() else: blockNumber = ui.verticalScrollBar1.value() except Exception, e: blockNumber = self.codeEditor.blockCount() Max = max(1, blockNumber) while (Max >= 10) : Max /= 10 digits += 1 space = 30 + self.codeEditor.fontMetrics().width('9') * digits return space #更新行號欄寬度 def updateWidth(self): width = self.getWidth() self.codeEditor.setViewportMargins(width, 0, 0, 0) #根據 updateRequest 信號 調整行號欄 def updateArea(self, rect, dy): if dy: self.scroll(0, dy) else: self.update(0, rect.y(), self.getWidth(), rect.height()) if (rect.contains(self.codeEditor.viewport().rect())): width = self.getWidth() self.codeEditor.setViewportMargins(width, 0, 0, 0) #繪製行號欄 def paintEvent(self, event): painter = QtGui.QPainter(self) rect = event.rect() painter.fillRect(rect, QtGui.QColor(243,243,243)) block = self.codeEditor.firstVisibleBlock() if ui.ui2isOpen: blockNumber = ui2.verticalScrollBar1.value() else: blockNumber = ui.verticalScrollBar1.value() top = int(self.codeEditor.blockBoundingGeometry(block).translated(self.codeEditor.contentOffset()).top()) bottom = top + int(self.codeEditor.blockBoundingRect(block).height()) while (block.isValid() and top <= rect.bottom()): if (block.isVisible() and bottom >= rect.top()): number = QtCore.QString.number(blockNumber + 1) painter.setPen(QtGui.QColor(59,153,181)) painter.drawText(0, top, self.codeEditor.lineNumberArea.width(), \ painter.fontMetrics().height(), \ QtCore.Qt.AlignVCenter|QtCore.Qt.AlignRight, number + ' ') block = block.next() top = bottom bottom = top + int(self.codeEditor.blockBoundingRect(block).height()) blockNumber += 1
而後重寫Edit類:ui
在Edit類的__init__()函數中:spa
一、定義一個行號欄類NumberBar類的對象self.lineNumberArea,而且爲信號添加如下事件:code
self.connect(self, QtCore.SIGNAL('blockCountChanged(int)'),\ self.lineNumberArea.updateWidth) self.connect(self, QtCore.SIGNAL('updateRequest(const QRect &, int)'),\ self.lineNumberArea.updateArea)
二、而後調用self.lineNumberArea的updateWidth()函數:對象
self.lineNumberArea.updateWidth()
效果:blog