Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
#ifndef KEYWORD_HIGHLIGHTER_H
#define KEYWORD_HIGHLIGHTER_H
#include 
<QSyntaxHighlighter>
#include 
<QTextCharFormat>
#include 
<QRegularExpression>
#include 
<QTextDocument>

class KeyWordHighlighter final : public QSyntaxHighlighter
{
    Q_OBJECT
public:
    KeyWordHighlighter(QTextDocument
* parent = nullptr);
    
void setKeyWords(const QStringList& keywords);
protected:
    
void highlightBlock(const QString& text)override;
private:
    
struct HighlightingRule
    {
        QRegularExpression pattern;
        QTextCharFormat format;
    };

    QVector
<HighlightingRule> highlightingRules;
    QTextCharFormat keywordFormat;
};

#include "KeyWordHighLighter.h"

KeyWordHighlighter::KeyWordHighlighter(QTextDocument* parent):
QSyntaxHighlighter(parent)
{
}

void KeyWordHighlighter::setKeyWords(const QStringList& words)
{
    HighlightingRule rule;

    keywordFormat.setForeground(Qt::black);
    keywordFormat.setFontWeight(QFont::Bold);

    foreach(auto word,words)
    {
        rule.pattern = QRegularExpression(word);
        rule.format = keywordFormat;
        highlightingRules.append(rule);
    }
}

void KeyWordHighlighter::highlightBlock(const QString& text)
{
    foreach(auto rule,highlightingRules)
    {
        QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
        while(matchIterator.hasNext())
        {
            QRegularExpressionMatch match = matchIterator.next();
            setFormat(match.capturedStart(),match.capturedLength(),rule.format);
        }
    }
}
posted on 2019-08-13 18:35 ccsdu2009 阅读(482) 评论(0)  编辑 收藏 引用 所属分类: QT编程

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理