Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_gui_text_qsyntaxhighlighter.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3#include <QChar>
4#include <QList>
5#include <QRegularExpression>
6#include <QSyntaxHighlighter>
7#include <QTextBlockUserData>
8#include <QTextEdit>
9#include <QTextObject>
10
13{
14 explicit MyHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { Q_UNUSED(document); }
15
16 void highlightBlock(const QString &text);
17 void wrapper();
18
20};
21
22//! [0]
24MyHighlighter *highlighter = new MyHighlighter(editor->document());
25//! [0]
26
27
28//! [1]
29void MyHighlighter::highlightBlock(const QString &text)
30{
31 QTextCharFormat myClassFormat;
32 myClassFormat.setFontWeight(QFont::Bold);
33 myClassFormat.setForeground(Qt::darkMagenta);
34
35 QRegularExpression expression("\\bMy[A-Za-z]+\\b");
36 QRegularExpressionMatchIterator i = expression.globalMatch(text);
37 while (i.hasNext()) {
38 QRegularExpressionMatch match = i.next();
39 setFormat(match.capturedStart(), match.capturedLength(), myClassFormat);
40 }
41}
42//! [1]
43
45//! [2]
46QTextCharFormat multiLineCommentFormat;
47multiLineCommentFormat.setForeground(Qt::red);
48
49QRegularExpression startExpression("/\\*");
50QRegularExpression endExpression("\\*/");
51
52setCurrentBlockState(0);
53
54int startIndex = 0;
55if (previousBlockState() != 1)
56 startIndex = text.indexOf(startExpression);
57
58while (startIndex >= 0) {
59 QRegularExpressionMatch endMatch;
60 int endIndex = text.indexOf(endExpression, startIndex, &endMatch);
61 int commentLength;
62 if (endIndex == -1) {
63 setCurrentBlockState(1);
64 commentLength = text.length() - startIndex;
65 } else {
66 commentLength = endIndex - startIndex
67 + endMatch.capturedLength();
68 }
69 setFormat(startIndex, commentLength, multiLineCommentFormat);
70 startIndex = text.indexOf(startExpression,
71 startIndex + commentLength);
72}
73//! [2]
74} // MyHighlighter::wrapper
75
76
77//! [3]
83
88//! [3]
89
90} // src_gui_text_qsyntaxhighlighter