Scintilla 是一个开源的源代码编辑器,带有语法高亮、区块折叠、代码提示、显示行号断点等众多功能,所以在文本编辑器领域相当流行。
PyQt 版的 Scintilla 叫 QsciScintilla ,被包含在
Qsci
模块中。
安装方法:pip install QScintilla
。🥗 创建自定义控件类 CodeWidget
继承自
Qsci.QsciScintilla
,使用方法类似于 Qt 自带的 QTextEdit。import Qsci class CodeWidget(Qsci.QsciScintilla): def __init__(self): super().__init__() self.setEolMode(self.SC_EOL_LF) # 以\n换行 self.setWrapMode(self.WrapWord) # 自动换行。self.WrapWord是父类QsciScintilla的 self.setAutoCompletionSource(self.AcsAll) # 自动补全。对于所有Ascii字符 self.setAutoCompletionCaseSensitivity(False) # 自动补全大小写敏感 self.setAutoCompletionThreshold(1) # 输入多少个字符才弹出补全提示 self.setFolding(True) # 代码可折叠 self.setFont(QtGui.QFont('Consolas', 12)) # 设置默认字体 # self.setMarginType(0, self.NumberMargin) # 0~4。第0个左边栏显示行号 # self.setMarginLineNumbers(0, True) # 我也不知道 # self.setMarginsBackgroundColor(QtGui.QColor(120, 220, 180)) # 边栏背景颜色 # self.setMarginWidth(0, 30) # 边栏宽度 self.setAutoIndent(True) # 换行后自动缩进 self.setUtf8(True) # 支持中文字符
🍧 设置语法着色方案
以 Html 为例:
def setSyntax(self): lexer = Qsci.QsciLexerHTML() # lexer.setDefaultFont(这里填 QFont 类型的字体) self.setLexer(lexer) # 关键是这句
🍦 还可以添加按键响应:
def keyPressEvent(self, e): ''' 和 QWidget 一样 ''' if e.key() == QtCore.Qt.Key_Escape: print ('hehe') super().keyPressEvent(e) def wheelEvent(self, e): ''' Ctrl + 滚轮 控制字体缩放 ''' if QtWidgets.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier: da = e.angleDelta() if da.y() > 0: self.zoomIn(1) # QsciScintilla 自带缩放的功能。参数是增加的字体点数 elif da.y() < 0: self.zoomOut(1) else: super().wheelEvent(e) # 留点汤给父类,不然滚轮无法翻页
🍡 使用方法:
code = CodeWidget() code.setText('<p>hahaha<a href="www.jianshu.com">hehe</a></p>')
Scintilla 的功能还有很多,这里是官网上的文档 :
🌱 https://www.scintilla.org/ScintillaDoc.html
Scintilla 内置了不少常用的代码高亮方案,如要自定义一套语法方案请看这里:https://www.jianshu.com/p/1677ad6e503dQsciScintilla 全部的语法解析器(Qt5.9):
QsciLexerAVS QsciLexerBash QsciLexerBatch QsciLexerCMake QsciLexerCPP QsciLexerCSS QsciLexerCSharp QsciLexerCoffeeScript QsciLexerD QsciLexerDiff QsciLexerFortran QsciLexerFortran77 QsciLexerHTML QsciLexerIDL QsciLexerJSON QsciLexerJava QsciLexerJavaScript QsciLexerLua QsciLexerMakefile QsciLexerMarkdown QsciLexerMatlab QsciLexerOctave QsciLexerPO QsciLexerPOV QsciLexerPascal QsciLexerPerl QsciLexerPostScript QsciLexerProperties QsciLexerPython QsciLexerRuby QsciLexerSQL QsciLexerSpice QsciLexerTCL QsciLexerTeX