语法高亮显示示例展现了如何执行简单的语法高亮显示(对C ++文件语法高亮)。
该示例主要使用QTextEdit和QSyntaxHighlighter实现。 html
要提供自定义的语法突出显示,您必须子类QSyntaxHighlighter
和从新实现highlightBlock
函数,并定义本身的突出显示规则。 app
使用QVector<HighlightingRule>
存储高亮显示规则:规则由QRegularExpression模式和QTextCharFormat实例组成,而后配置好的highlightingRules
,用于当文本块更新时自动调用highlightBlock
函数刷新高亮显示文本。函数
struct HighlightingRule { QRegularExpression pattern; QTextCharFormat format; }; QVector<HighlightingRule> highlightingRules;
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); } } ... }
高亮显示文本格式有:spa
QTextCharFormat keywordFormat; // 关键词 QTextCharFormat classFormat; // 类名 QTextCharFormat singleLineCommentFormat; // 单行注释 QTextCharFormat multiLineCommentFormat; // 多行注释 QTextCharFormat quotationFormat; // 头文件引用 QTextCharFormat functionFormat; // 函数
以添加类名高亮语法为例:code
HighlightingRule rule; classFormat.setFontWeight(QFont::Bold); classFormat.setForeground(Qt::darkMagenta); rule.pattern = QRegularExpression("\\bQ[A-Za-z]+\\b"); // 配置"类名"正则模式 rule.format = classFormat; // 配置"类名"的文本格式 highlightingRules.append(rule); // 添加到高亮显示规则容器,用于文本刷新
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\widgets\richtext\syntaxhighlighter
https://doc.qt.io/qt-5/qtwidgets-richtext-syntaxhighlighter-example.html