PyQt6实战6--高亮

本文介绍了如何在PyQt6中使用QTextEdit和QSyntaxHighlighter扩展SQL查询器功能,实现SQL语句的高亮显示,提升代码可读性。
摘要由CSDN通过智能技术生成

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 _format

STYLES = {
    '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 rules
        rules += [(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 formatting
        for 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

公众号:

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值