Почему у меня не показывает нумерация не показывается в QPlainTextEdit в PyQt5
вот файл
import sys
import un
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import Qt
class LineNumberArea(Qt.QWidget):
def __init__(self, editor):
super().__init__(editor)
self.myeditor = editor
def sizeHint(self):
return Qt.QSize(self.myeditor.lineNumberAreaWidth(), 0)
def paintEvent(self, event):
self.myeditor.lineNumberAreaPaintEvent(event)
class CodeEditor(Qt.QPlainTextEdit):
def __init__(self):
super().__init__()
self.button = QCommandLinkButton('Desing', self)
self.button.setStyleSheet('border: 0px; padding: 0px;')
self.button.setCursor(Qt.Qt.ArrowCursor)
self.button.resize(91, 40)
self.setStyleSheet("""font-family:'Consolas';
color:#ccc;
font-size: 20px;
background-color:#2b2b2b;""")
self.lineNumberArea = LineNumberArea(self)
self.blockCountChanged[int].connect(self.updateLineNumberAreaWidth)
self.updateRequest[Qt.QRect,int].connect(self.updateLineNumberArea)
self.cursorPositionChanged.connect(self.highlightCurrentLine)
self.updateLineNumberAreaWidth()
self.completer = un.MyCompleter()
self.completer.setWidget(self)
self.completer.insertText.connect(self.insertCompletion)
def insertCompletion(self, completion):
tc = self.textCursor()
extra = (len(completion) - len(self.completer.completionPrefix()))
tc.movePosition(QTextCursor.Left)
tc.movePosition(QTextCursor.EndOfWord)
tc.insertText(completion[-extra:])
self.setTextCursor(tc)
self.completer.popup().hide()
def focusInEvent(self, event):
if self.completer:
self.completer.setWidget(self)
QPlainTextEdit.focusInEvent(self, event)
def keyPressEvent(self, event):
tc = self.textCursor()
if event.key() == QtCore.Qt.Key_Tab and self.completer.popup().isVisible():
self.completer.insertText.emit(self.completer.getSelected())
self.completer.setCompletionMode(QCompleter.PopupCompletion)
return
QPlainTextEdit.keyPressEvent(self, event)
tc.select(QTextCursor.WordUnderCursor)
cr = self.cursorRect()
if len(tc.selectedText()) > 0:
self.completer.setCompletionPrefix(tc.selectedText())
popup = self.completer.popup()
popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
cr.setWidth(self.completer.popup().sizeHintForColumn(0)
+ self.completer.popup().verticalScrollBar().sizeHint().width())
self.completer.complete(cr)
else:
self.completer.popup().hide()
def lineNumberAreaWidth(self):
digits = 1
count = max(1, self.blockCount())
while count >= 10:
count /= 10
digits += 1
space = 3 + self.fontMetrics().width('9') * digits
return space
def updateLineNumberAreaWidth(self):
self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)
def updateLineNumberArea(self, rect, dy):
if dy:
self.lineNumberArea.scroll(0, dy)
else:
self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(),
rect.height())
if rect.contains(self.viewport().rect()):
self.updateLineNumberAreaWidth()
def resizeEvent(self, event):
super().resizeEvent(event)
cr = self.contentsRect();
self.lineNumberArea.setGeometry(Qt.QRect(cr.left(), cr.top(),
self.lineNumberAreaWidth(), cr.height()))
def lineNumberAreaPaintEvent(self, event):
mypainter = Qt.QPainter(self.lineNumberArea)
mypainter.setBackground(Qt.QColor(Qt.Qt.green))
mypainter.setFont(Qt.QFont("", 15))
mypainter.fillRect(event.rect(), Qt.Qt.lightGray)
block = self.firstVisibleBlock()
blockNumber = block.blockNumber()
top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()
bottom = top + self.blockBoundingRect(block).height()
height = self.fontMetrics().height()
while block.isValid() and (top <= event.rect().bottom()):
if block.isVisible() and (bottom >= event.rect().top()):
number = str(blockNumber + 1)
mypainter.setPen(Qt.Qt.black)
mypainter.drawText(0, int(top), self.lineNumberArea.width(), height,
Qt.Qt.AlignRight, number)
block = block.next()
top = bottom
bottom = top + self.blockBoundingRect(block).height()
blockNumber += 1
def highlightCurrentLine(self):
extraSelections = []
if not self.isReadOnly():
selection = Qt.QTextEdit.ExtraSelection()
#Qt.Qt.green
lineColor = Qt.QColor('#2d2d2d').lighter(160)
selection.format.setBackground(lineColor)
selection.format.setProperty(Qt.QTextFormat.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
extraSelections.append(selection)
self.setExtraSelections(extraSelections)
def resizeEvent(self, event):
buttonSize = self.button.sizeHint()
frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
print(buttonSize.width(), buttonSize.height(), frameWidth)
#print(self.rect().right() - frameWidth - buttonSize.width() - buttonSize.height())
#print((self.rect().bottom() - buttonSize.height() + 1) / 2)
#print(self.rect().bottom() - buttonSize.height() - buttonSize.width() + 1)
#print(self.rect().bottom(), self.rect().right())
self.button.move(int(self.rect().right() - 111), 2)
super(CodeEditor, self).resizeEvent(event)
if __name__ == "__main__":
app = Qt.QApplication(sys.argv)
txt = CodeEditor()
#txt.buttonClicked.connect(text2_clic)
highlight = un.PythonHighlighter(txt.document())
infile = open('un.py', 'r')
txt.setPlainText(infile.read())
txt.setStyleSheet("""font-family:'Consolas';
color: #ccc;
font-size: 20px;
background-color: #2b2b2b;""")
txt.setGeometry(400, 100, 600, 400)
txt.show()
sys.exit(app.exec_())
вот файл un.py
from PyQt5.QtGui import *
from PyQt5.QtCore import *
def format(color, style=''):
""" Верните QTextCharFormat с указанными атрибутами. """
_color = QColor()
_color.setNamedColor(color)
_format = QTextCharFormat()
_format.setForeground(_color)
if 'bold' in style:
_format.setFontWeight(QFont.Bold)
if 'italic' in style:
_format.setFontItalic(True)
return _format
# Синтаксические стили, которые могут использоваться
STYLES = {
'moduls' : format('lime'),
'keyword': format('cyan'),
#'func': format('cyan'),
'operator': format('white'),
'brace': format('darkGray'),
'defclass': format('cyan'),
'string': format('yellow'),
'string2': format('yellow'),
'comment': format('green'),
#'permen': format('greenyellow'),
#'permenposle': format('cyan'),
'self': format('orange'),
'numbers': format('purple'),
}
class PythonHighlighter (QSyntaxHighlighter):
"""Синтаксические маркеры для языка Python. """
# Python keywords
import sys
moduls = []
for i in sys.stdlib_module_names:
moduls.append(i)
keywords = ['and', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'exec', 'finally',
'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'not', 'or', 'pass', 'print',
'raise', 'return', 'try', 'while', 'yield',
'None', 'True', 'False']
# Python operators
operators = [
'=',
# Comparison
'==', '!=', '<', '<=', '>', '>=',
# Arithmetic
'\+', '-', '\*', '/', '//', '\%', '\*\*',
# In-place
'\+=', '-=', '\*=', '/=', '\%=',
# Bitwise
'\^', '\|', '\&', '\~', '>>', '<<',
]
# Python braces
braces = [
'\{', '\}', '\(', '\)', '\[', '\]',
]
def __init__(self, document):
QSyntaxHighlighter.__init__(self, document)
self.tri_single = (QRegExp("'''"), 1, STYLES['string'])
self.tri_double = (QRegExp('"""'), 2, STYLES['string2'])
rules = []
# Keyword, operator, and brace rules
rules += [(r'\b%s\b' % w, 0, STYLES['keyword'])
for w in PythonHighlighter.keywords]
rules += [(r'\b%s\b' % w, 0, STYLES['moduls'])
for w in PythonHighlighter.moduls]
rules += [(r'%s' % o, 0, STYLES['operator'])
for o in PythonHighlighter.operators]
rules += [(r'%s' % b, 0, STYLES['brace'])
for b in PythonHighlighter.braces]
# All other rules
rules += [
(r'\bself\b', 0, STYLES['self']),
#(r'\bself\b', 0, STYLES['self']),
(r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
(r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
(r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
(r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),
(r'#[^\n]*', 0, STYLES['comment']),
#(r"=[^'\\]*(\\.[^'\\]*)*", 0, STYLES['permenposle']),
#(r'=[^"\\]*(\\.[^"\\]*)*', 0, STYLES['permenposle']),
#(r'\.[^\n]*\s*(\w+)', 0, STYLES['func']),
#(r'[^"\\\.]*(\\.[^"\\\.]*)*=', 0, STYLES['permen']),
#(r'(.[^(from)|(if)])*\.', 1, STYLES['permen']),
(r'\b[+-]?[0-9]+[lL]?\b', 0, STYLES['numbers']),
(r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b', 0, STYLES['numbers']),
(r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b',0, STYLES['numbers']),
]
# Создайте QRegExp для каждого шаблона
self.rules = [(QRegExp(pat), index, fmt)
for (pat, index, fmt) in rules]
def highlightBlock(self, text):
"""Применить выделение синтаксиса к данному блоку текста. """
# Сделайте другое форматирование синтаксиса
for expression, nth, format in self.rules:
index = expression.indexIn(text, 0)
while index >= 0:
index = expression.pos(nth)
length = len(expression.cap(nth))
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
# Многострочные строки
in_multiline = self.match_multiline(text, *self.tri_single)
if not in_multiline:
in_multiline = self.match_multiline(text, *self.tri_double)
def match_multiline(self, text, delimiter, in_state, style):
if self.previousBlockState() == in_state:
start = 0
add = 0
else:
start = delimiter.indexIn(text)
add = delimiter.matchedLength()
while start >= 0:
end = delimiter.indexIn(text, start + add)
if end >= add:
length = end - start + add + delimiter.matchedLength()
self.setCurrentBlockState(0)
else:
self.setCurrentBlockState(in_state)
length = len(text) - start + add
self.setFormat(start, length, style)
start = delimiter.indexIn(text, start + length)
if self.currentBlockState() == in_state:
return True
else:
return False
from PyQt5.QtWidgets import QCompleter
from PyQt5 import QtCore
class MyCompleter(QCompleter):
insertText = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
import sys
moduls = []
for i in sys.stdlib_module_names:
moduls.append(i)
sit = ['and', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'exec', 'finally',
'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'not', 'or', 'pass', 'print',
'raise', 'return', 'try', 'while', 'yield',
'None', 'True', 'False']
for s in sit:
moduls.append(s)
QCompleter.__init__(self, moduls, parent)
self.setCompletionMode(QCompleter.PopupCompletion)
self.highlighted.connect(self.setHighlighted)
def setHighlighted(self, text):
self.lastSelected = text
def getSelected(self):
return self.lastSelected
Это как компилятор