語法高亮顯示示例展現瞭如何執行簡單的語法高亮顯示(對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