-
Notifications
You must be signed in to change notification settings - Fork 0
/
highlighter.cpp
45 lines (36 loc) · 1.29 KB
/
highlighter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "highlighter.h"
#include <QDebug>
#include <QRegExp>
#include <QTextCharFormat>
Highlighter::Highlighter(QTextDocument* parent) : QSyntaxHighlighter(parent) {
HighlightingRule rule;
int red = 255;
int green = 140;
int blue = 0;
// JSON keys
keyFormat.setForeground(Qt::red);
rule.pattern = QRegExp("\"(\\w+)\"\\s*:");
rule.format = keyFormat;
highlightingRules.append(rule);
// JSON strings
stringFormat.setForeground(Qt::darkGreen); // Change to the desired color for strings
rule.pattern = QRegExp("\"([^\"]*)\"");
rule.format = stringFormat;
highlightingRules.append(rule);
// JSON numbers
numberFormat.setForeground(Qt::darkMagenta); // Change to the desired color for numbers
rule.pattern = QRegExp("\\b-?\\d+(\\.\\d+)?([eE][-+]?\\d+)?\\b");
rule.format = numberFormat;
highlightingRules.append(rule);
}
void Highlighter::highlightBlock(const QString& text) {
foreach (const HighlightingRule& rule, highlightingRules) {
QRegExp expression(rule.pattern);
int index = text.indexOf(expression);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = text.indexOf(expression, index + length);
}
}
}