from PySide2.QtCore import Qt, QRegExp
from PySide2.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter
from PySide2.QtWidgets import QApplication, QMainWindow, QPlainTextEdit
class PythonHighlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super().__init__(parent)
keyword_format = QTextCharFormat()
keyword_format.setForeground(Qt.red)
keyword_format.setFontWeight(QFont.Bold)
keyword_patterns = [
"\\bFalse\\b", "\\bNone\\b", "\\bTrue\\b",
"\\band\\b", "\\bas\\b", "\\bassert\\b",
"\\bbreak\\b", "\\bclass\\b", "\\bcontinue\\b",
"\\bdef\\b", "\\bdel\\b", "\\belif\\b", "\\belse\\b",
"\\bexcept\\b", "\\bfinally\\b", "\\bfor\\b",
"\\bfrom\\b", "\\bglobal\\b", "\\bif\\b",
"\\bimport\\b", "\\bin\\b", "\\bis\\b",
"\\blambda\\b", "\\bnonlocal\\b", "\\bnot\\b",
"\\bor\\b", "\\bpass\\b", "\\braise\\b",
"\\breturn\\b", "\\btry\\b", "\\bwhile\\b",
"\\bwith\\b", "\\byield\\b"
]
self.highlighting_rules = [(QRegExp(pattern), keyword_format)
for pattern in keyword_patterns]
class_format = QTextCharFormat()
class_format.setFontWeight(QFont.Bold)
class_format.setForeground(Qt.darkMagenta)
self.highlighting_rules.append((QRegExp("\\bQ[A-Za-z]+\\b"),
class_format))
quotation_format = QTextCharFormat()
quotation_format.setForeground(Qt.darkGreen)
self.highlighting_rules.append((QRegExp("\".*\""), quotation_format))
self.highlighting_rules.append((QRegExp("\'.*\'"), quotation_format))
function_format = QTextCharFormat()
function_format.setFontItalic(True)
function_format.setForeground(Qt.blue)
self.highlighting_rules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
function_format))
def highlightBlock(self, text):
for pattern, format in self.highlighting_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)
class CodeEditor(QPlainTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
font = QFont()
font.setFamily('Courier')
font.setFixedPitch(True)
font.setPointSize(10)
self.setFont(font)
highlighter = PythonHighlighter(self.document())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.editor = CodeEditor()
self.setCentralWidget(self.editor)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
它包含了一些正则表达式和格式化规则,用于高亮Python代码中的关键字、类、函数和字符串。然后,我们创建了一个名为CodeEditor的自定义QPlainTextEdit类,它使用PythonHighlighter来高亮文本。最后,我们创建了一个名为MainWindow的主窗口,并将CodeEditor设置为其中央部件。