PyQt6实战3--sql查询器-CSDN博客
在sql查询器的基础上添加了sql语法的高亮
运行效果:
代码:
只需要在原来的代码上添加一行
rightTopLayout = QVBoxLayout()rightTopLayout.addWidget(QLabel("输入sql:"))self.sql = QTextEdit()
#加一行高亮,把edit的document穿进去即可self.highlighter = SqlHighlighter(self.sql.document())rightTopLayout.addWidget(self.sql, stretch=2)self.queryLayout = QHBoxLayout()self.query_button = QPushButton("查询")self.queryLayout.addWidget(self.query_button)
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
from PyQt6.QtCore import *def format(color, style=''):"""Return a QTextCharFormat with the given attributes."""_color = QColor()if type(color) is not str:_color.setRgb(color[0], color[1], color[2])else:_color.setNamedColor(color)_format = QTextCharFormat()_format.setForeground(_color)if 'bold' in style:_format.setFontWeight(QFont.Weight.Bold)if 'italic' in style:_format.setFontItalic(True)return _formatSTYLES = {'keyword': format([200, 120, 50], 'bold'),'operator': format([150, 150, 150]),'brace': format('darkGray'),'defclass': format([220, 220, 255], 'bold'),'string': format([20, 110, 100]),'string2': format([30, 120, 110]),'comment': format([128, 128, 128]),'self': format([150, 85, 140], 'italic'),'numbers': format([100, 150, 190]),
}class SqlHighlighter(QSyntaxHighlighter):keywords = ['select', 'from', 'update', 'where', 'set', 'order', 'by', 'group', 'having','insert', 'into', 'delete', 'create', 'table', 'drop', 'alter', 'index','and', 'or', 'not', 'like', 'between', 'is', 'null', 'distinct','count', 'sum', 'avg', 'max', 'min', 'limit', 'offset', 'join','inner', 'outer', 'left', 'right', 'on', 'as', 'desc', 'asc']braces = ['\{', '\}', '\(', '\)', '\[', '\]',]def __init__(self, document):super().__init__(document)rules = []# Keyword, operator, and brace rulesrules += [(r'\b%s\b' % w, 0, STYLES['keyword'])for w in SqlHighlighter.keywords]rules += [(r'%s' % b, 0, STYLES['brace'])for b in SqlHighlighter.braces]self.rules = [(QRegularExpression(pat), index, fmt) for (pat, index, fmt) in rules]def highlightBlock(self, text: str) -> None:"""Apply syntax highlighting to the given block of text."""# Do other syntax formattingfor expression, nth, format in self.rules:matchIterator = expression.globalMatch(text)while matchIterator.hasNext():# print(rule.pattern.pattern())match = matchIterator.next()self.setFormat(match.capturedStart(), match.capturedLength(), format)self.setCurrentBlockState(0)
代码地址
GitHub - chunlaiqingke/Tiny-Tool
公众号: