前篇文章, 我们实现了client子窗口的整体功能:
压测工具开发实战篇(六)——client子窗口整体功能
我们发现在文本编辑框中写的代码并没有高亮显示, 看起来不美观, 怎么实现文本框中代码高亮显示呢?
问了 Chat老师, 我们可以在项目中新建一个模块, 用于存放实现代码高亮的功能代码:
# syntaxhighlighter.py
import sys
from PySide6.QtCore import QRegularExpression
from PySide6.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter
def format(color, style=''):
"""Return a QTextCharFormat with the given attributes."""
_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
# Syntax styles that can be shared by all languages
STYLES = {
'keyword': format('blue'),
'operator': format('red'),
'brace': format('darkRed'),
'defclass': format('black', 'bold'),
'string': format('darkGreen'),
'string2': format('darkGreen'),
'comment': format('darkGray'),
'self': format('darkRed'),
'numbers': format('brown'),
}
class PythonHighlighter(QSyntaxHighlighter):
"""Syntax highlighter for the Python language."""
# Python keywords
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):
super().__init__(document)
# Multi-line strings (expression, flag, style)
self.tri_single = (QRegularExpression("'''"), 1, STYLES['string2'])
self.tri_double = (QRegularExpression('"""'), 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'%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 += [
# 'self'
(r'\bself\b', 0, STYLES['self']),
# Double-quoted string, possibly containing escape sequences
(r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
# Single-quoted string, possibly containing escape sequences
(r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
# 'def' followed by an identifier
(r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
# 'class' followed by an identifier
(r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),
# From '#' until a newline
(r'#[^\n]*', 0, STYLES['comment']),
# Numeric literals
(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']),
]
# Build a QRegularExpression for each pattern
self.rules = [(QRegularExpression(pat), index, fmt)
for (pat, index, fmt) in rules]
def highlightBlock(self, text):
"""Apply syntax highlighting to the given block of text."""
# Do other syntax formatting
for expression, nth, format in self.rules:
match_iterator = expression.globalMatch(text) # 使用 globalMatch 获取迭代器
while match_iterator.hasNext(): # 检查是否有下一个匹配项
match = match_iterator.next() # 获取下一个匹配项
if match.hasMatch() and match.captured(nth):
start = match.capturedStart(nth)
length = match.capturedLength(nth)
self.setFormat(start, length, format)
self.setCurrentBlockState(0)
# Do multi-line strings
in_multiline = self.match_multiline(text, *self.tri_single)
if not in_multiline:
in_multiline = self.match_multiline(text, *self.tri_double)
# Do multi-line strings
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):
"""Do highlighting of multi-line strings. ``delimiter`` should be a
``QRegularExpression`` for triple-single-quotes or triple-double-quotes, and
``in_state`` should be a unique integer to represent the corresponding
state changes when inside those strings. Returns True if we're still
inside a multi-line string when this function is finished.
"""
# If inside triple-single quotes, start at 0
if self.previousBlockState() == in_state:
start = 0
add = 0
# Otherwise, look for the delimiter on this line
else:
match = delimiter.match(text)
start = match.capturedStart() if match.hasMatch() else -1
add = match.capturedLength() if match.hasMatch() else 0
# As long as there's a delimiter match on this line...
while start >= 0:
# Look for the ending delimiter
match = delimiter.match(text, start + add)
end = match.capturedStart() if match.hasMatch() else -1
# Ending delimiter on this line?
if end >= add:
length = end - start + add + match.capturedLength() if match.hasMatch() else 0
self.setCurrentBlockState(0)
# No; multi-line string
else:
self.setCurrentBlockState(in_state)
length = len(text) - start + add
# Apply formatting
self.setFormat(start, length, style)
# Look for the next match
match = delimiter.match(text, start + length)
start = match.capturedStart() if match.hasMatch() else -1
# Return True if still inside a multi-line string, False otherwise
return self.currentBlockState() == in_state
我们在client.py中使用已经实现好的代码高亮功能, 只需要导入即可:
# client.py
from lib.syntaxhighlighter import PythonHighlighter
class Client:
def __init__(self):
...
# 编辑框文本高亮显示
self.highlighter = PythonHighlighter(self.ui.te_code.document())
...
这样实现之后, 文本编辑框中的代码就可以高亮显示了: