嗨,我有一个疑问,为什么这段代码不起作用?
def format(color, style=''):
_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 = {
'keyword': format('darkBlue'),
'operator': format('red'),
'comment': format('darkGreen'),
'brace': format('darkGray'),
'function': format('yellow'),
'string': format('green'),
'numbers': format('blue')
}
class Highlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(Highlighter, self).__init__(parent)
xml_read.read_keywords_from_xml(self)
array_from_xml = xml_read.xmldata
self.rules = []
self.rules += [(QRegExp(pattern), STYLES['keyword'])for pattern in
array_from_xml[0]]
self.rules += [(QRegExp(func), STYLES['function'])for func in
array_from_xml[4]]
self.rules += [(QRegExp(operator), STYLES['operator'])for operator in
array_from_xml[1]]
self.rules.append((QRegExp("//[^\n]*"), STYLES['comment']))
self.rules += [
# Numeric light
(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']),
]
self.commentStartExpression = QRegExp("/*\\")
self.commentEndExpression = QRegExp("\\*/")
def highlightBlock(self, text):
for pattern, format in self.rules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index+length)
self.setCurrentBlockState(0)
startindex = 0
if self.previousBlockState() != 1:
startindex = self.commentStartExpression.indexIn(text)
while startindex >= 0:
endIndex = self.commentEndExpression.indexIn(text, startindex)
if endIndex == -1:
self.setCurrentBlockState(1)
commentlenght = len(text) - startindex
else:
commentlenght = endIndex - startindex + self.commentEndExpression.matchedLength()
self.setFormat(startindex, commentlenght,
self.multiLineCommentFormat)
startindex = self.commentStartExpression.indexIn(text,
startindex + commentlenght)
我想将HighLight添加到我的文本编辑器(https://github.com/VarusEx/DEdit/tree/Syntax_Highlighter)中,我很早就这样做了,那写得不好,然后我决定重写他,现在我遇到了问题。代码几乎相同,但是现在从xml文件读取表,并且该表位于主应用程序文件的后面。我真的没看到问题,没有错误就是行不通。