Qt QTextEdit 语法高亮

QTextEdit 语法高亮

Qt 提供了 QSyntaxHighlighter 类 来实现语法高亮,Qt 提供了一个例子 讲解继承 QSyntaxHighlighter 来自定义自己的语法高亮格式
Qt QTextEdit 语法高亮_第1张图片
这里写图片描述

highlighter.h


#ifndef HIGHLIGHTER_H
#define HIGHLIGHTER_H

#include 
#include 
#include 

QT_BEGIN_NAMESPACE
class QTextDocument;
QT_END_NAMESPACE

//! [0]
class Highlighter : public QSyntaxHighlighter //继承QSyntaxHightliaghter
{
    Q_OBJECT

public:
    Highlighter(QTextDocument *parent = 0);//构造函数传一个 QTextDocument 对象 给父类

protected:
    void highlightBlock(const QString &text) override;//重写父类这个函数 自动调用

private:

    struct HighlightingRule//语法规则结构体,包含正则表达式模式串和匹配的样式  
    {
        QRegularExpression pattern;
        QTextCharFormat format;
    };
    QVector highlightingRules;//规则的集合,可以定义多个高亮规则

    QRegularExpression commentStartExpression; //注释的高亮,使用highliangBlock()匹配,下文提到
    QRegularExpression commentEndExpression;

    QTextCharFormat keywordFormat;//高亮样式,关键词,一下顾名思义
    QTextCharFormat classFormat;
    QTextCharFormat singleLineCommentFormat;
    QTextCharFormat multiLineCommentFormat;
    QTextCharFormat quotationFormat;
    QTextCharFormat functionFormat;
};
//! [0]

#endif // HIGHLIGHTER_H

highlighter.cpp

#include "highlighter.h"

//! [0]
Highlighter::Highlighter(QTextDocument *parent)
    : QSyntaxHighlighter(parent)
{
    HighlightingRule rule;

    keywordFormat.setForeground(Qt::darkBlue);//设定关键词的高亮样式
    keywordFormat.setFontWeight(QFont::Bold);
    QStringList keywordPatterns; //关键词集合,关键都以正则表达式表示 下面的可以改为我们想要的关键词
    keywordPatterns << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b"
                    << "\\bdouble\\b" << "\\benum\\b" << "\\bexplicit\\b"
                    << "\\bfriend\\b" << "\\binline\\b" << "\\bint\\b"
                    << "\\blong\\b" << "\\bnamespace\\b" << "\\boperator\\b"
                    << "\\bprivate\\b" << "\\bprotected\\b" << "\\bpublic\\b"
                    << "\\bshort\\b" << "\\bsignals\\b" << "\\bsigned\\b"
                    << "\\bslots\\b" << "\\bstatic\\b" << "\\bstruct\\b"
                    << "\\btemplate\\b" << "\\btypedef\\b" << "\\btypename\\b"
                    << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvirtual\\b"
                    << "\\bvoid\\b" << "\\bvolatile\\b" << "\\bbool\\b";
    foreach (const QString &pattern, keywordPatterns) {
        rule.pattern = QRegularExpression(pattern);
        rule.format = keywordFormat;
        highlightingRules.append(rule);
//! [0] //! [1]
    }
//! [1]

//! [2]
    classFormat.setFontWeight(QFont::Bold);//添加Qt的类到高亮规则中
    classFormat.setForeground(Qt::darkMagenta);
    rule.pattern = QRegularExpression("\\bQ[A-Za-z]+\\b");
    rule.format = classFormat;
    highlightingRules.append(rule);
//! [2]

//! [3]
    singleLineCommentFormat.setForeground(Qt::red);//单行注释
    rule.pattern = QRegularExpression("//[^\n]*");
    rule.format = singleLineCommentFormat;
    highlightingRules.append(rule);

    multiLineCommentFormat.setForeground(Qt::red);//多行注释,只设定了样式,具体匹配在highlightBlock中设置
//! [3]

//! [4]
    quotationFormat.setForeground(Qt::darkGreen);//字符串
    rule.pattern = QRegularExpression("\".*\"");
    rule.format = quotationFormat;
    highlightingRules.append(rule);
//! [4]

//! [5]
    functionFormat.setFontItalic(true);//函数
    functionFormat.setForeground(Qt::blue);
    rule.pattern = QRegularExpression("\\b[A-Za-z0-9_]+(?=\\()");
    rule.format = functionFormat;
    highlightingRules.append(rule);
//! [5]

//! [6]
    commentStartExpression = QRegularExpression("/\\*");//多行注释的匹配正则表达式
    commentEndExpression = QRegularExpression("\\*/");
}
//! [6]

//! [7]
void Highlighter::highlightBlock(const QString &text)//应用高亮规则,也用于区块的高亮,比如多行注释
{
    foreach (const HighlightingRule &rule, highlightingRules) {//文本采用高亮规则
        QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
        while (matchIterator.hasNext()) {
            QRegularExpressionMatch match = matchIterator.next();
            setFormat(match.capturedStart(), match.capturedLength(), rule.format);
        }
    }
//! [7] //! [8]
    setCurrentBlockState(0); //以下是多行注释的匹配
//! [8]

//! [9]
    int startIndex = 0;
    if (previousBlockState() != 1)
        startIndex = text.indexOf(commentStartExpression);

//! [9] //! [10]
    while (startIndex >= 0) {
//! [10] //! [11]
        QRegularExpressionMatch match = commentEndExpression.match(text, startIndex);
        int endIndex = match.capturedStart();
        int commentLength = 0;
        if (endIndex == -1) {
            setCurrentBlockState(1);
            commentLength = text.length() - startIndex;
        } else {
            commentLength = endIndex - startIndex
                            + match.capturedLength();
        }
        setFormat(startIndex, commentLength, multiLineCommentFormat);
        startIndex = text.indexOf(commentStartExpression, startIndex + commentLength);
    }
}
//! [11]

使用很简单

QTextEdit* pEdit = new QTextEdit();

Highlighter * h = new Highlighter(pEdit->document());//传一个QTextDocument 

Qt QTextEdit 语法高亮_第2张图片

    98年菜鸡一枚,请大佬们多多关照!

你可能感兴趣的:(Qt)