#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);
}
}
}