Qt文本高亮显示QSyntaxHighlighter

1. QSyntaxHighlighter

通过对每个文本块应用高亮规则,将匹配的文本部分格式化。文本块可以是行、段落或其它的文本区域。

常用的函数和功能

highlightBlock:这是一个纯虚函数,开发者需要重写这个方法来定义文本的高亮规则。setFormat:用于为文本区域设置格式,包括字体、颜色等。

rehighlight:重新应用高亮规则。

currentBlockState、previousBlockState:管理文本块的状态。

setDocument、document:设置和获取高亮所作用的文档对象。

2. 示例代码讲解(代码来源:明王讲Qt例子)修改

在这个示例中,我们创建了一个名为 MyHighlighter 的类,它继承自 QSyntaxHighlighter,并定义了几种高亮规则。这些规则用于突出显示特定的文本部分,例如时间、温度、湿度和报警状态。

MyHighlighter 类的实现

cpp 复制代码
#include "MyHighlighter.h"
#include <QDebug>
#define tc(a) QString::fromLocal8Bit(a)  // 将本地8位字符转换为QString

MyHighlighter::MyHighlighter(QTextDocument* parent)
    : QSyntaxHighlighter(parent) {
    HighlightingRule rule;  // 定义高亮规则对象

    // 时间的高亮规则
    rule.pattern = QRegularExpression(R"(\[.*\])");
    timeFormat.setForeground(QColor(85, 85, 85));  // 设置字体颜色为灰色
    timeFormat.setBackground(QColor(240, 240, 240));  // 设置背景色为浅灰色
    timeFormat.setFontWeight(QFont::Bold);  // 设置字体为加粗
    timeFormat.setFontFamily("Consolas");  // 设置字体为Consolas
    rule.format = timeFormat;
    highlightingRules.push_back(rule);

    // 温度的高亮规则
    rule.pattern = QRegularExpression("温度");
    tempKeyFormat.setForeground(QColor(180, 30, 110));  // 设置字体颜色为紫色
    tempKeyFormat.setFontFamily("Consolas");
    rule.format = tempKeyFormat;
    highlightingRules.push_back(rule);

    // 温度值的高亮规则
    rule.pattern = QRegularExpression(tc(R"((?<=温度:)\s*-*\d+°C)"));
    tempValueFormat.setForeground(QColor(180, 30, 110));  // 设置字体颜色为紫色
    tempValueFormat.setFontWeight(QFont::Bold);
    tempValueFormat.setFontFamily("Consolas");
    rule.format = tempValueFormat;
    highlightingRules.push_back(rule);

    // 湿度的高亮规则
    rule.pattern = QRegularExpression("湿度");
    humiKeyFormat.setForeground(QColor(97, 54, 134));  // 设置字体颜色为紫色
    humiKeyFormat.setFontFamily("Consolas");
    rule.format = humiKeyFormat;
    highlightingRules.push_back(rule);

    // 湿度值的高亮规则
    rule.pattern = QRegularExpression(tc(R"((?<=湿度:)\s*\d+%)"));
    humiValueFormat.setForeground(QColor(97, 54, 134));  // 设置字体颜色为紫色
    humiValueFormat.setFontWeight(QFont::Bold);
    humiValueFormat.setFontFamily("Consolas");
    rule.format = humiValueFormat;
    highlightingRules.push_back(rule);

    // 报警:正常
    rule.pattern = QRegularExpression(tc("(正常)"));
    normalFormat.setForeground(Qt::darkGreen);
    normalFormat.setFontFamily("Consolas");
    rule.format = normalFormat;
    highlightingRules.push_back(rule);

    // 报警:下限
    rule.pattern = QRegularExpression(tc("(↓过低)"));
    lowerFormat.setForeground(Qt::white);
    lowerFormat.setBackground(Qt::darkBlue);
    lowerFormat.setFontWeight(QFont::Bold);
    lowerFormat.setFontFamily("Consolas");
    rule.format = lowerFormat;
    highlightingRules.push_back(rule);

    // 报警:上限
    rule.pattern = QRegularExpression(tc("(↑过高)"));
    upperFormat.setForeground(Qt::white);
    upperFormat.setBackground(QColor(220, 50, 50));
    upperFormat.setFontWeight(QFont::Bold);
    upperFormat.setFontFamily("Consolas");
    rule.format = upperFormat;
    highlightingRules.push_back(rule);
}

void MyHighlighter::highlightBlock(const QString& text) {
    for (HighlightingRule& rule : highlightingRules) {
        QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
        while (matchIterator.hasNext()) {
            QRegularExpressionMatch match = matchIterator.next();
            setFormat(match.capturedStart(), match.capturedLength(), rule.format);
        }
    }
}

2.1 构造函数与规则定义

在 MyHighlighter 的构造函数中,我们定义了多个高亮规则。每个规则包含一个正则表达式和一个格式。我们用不同的格式来高亮显示时间、温度、湿度以及报警状态:

时间:匹配方括号内的内容(如 [12:30]),设置灰色字体和浅灰色背景。

温度:匹配 温度 字符串,使用紫色字体。

湿度:匹配 湿度 字符串,使用紫色字体。

报警状态:根据报警类型(正常、过低、过高)设置不同的颜色和字体样式。

2.2 highlightBlock 函数

highlightBlock 函数是 QSyntaxHighlighter 类的核心方法。在这个方法中,我们遍历定义好的高亮规则,通过正则表达式来匹配文本中的特定部分。对于每个匹配到的部分,调用 setFormat 来设置它的格式。

3. QSyntaxHighlighter 类的其他常用方法

3.1 setDocument 和 documentsetDocument

用于将一个 QTextDocument 对象与高亮器关联,document 用于获取当前文档。

cpp 复制代码
void setDocument(QTextDocument *doc);
QTextDocument *document() const;

3.2 rehighlight 和 rehighlightBlock

rehighlight:重新高亮整个文档。

rehighlightBlock:只重新高亮某个文本块。

这些函数对于在文本内容发生变化时重新应用高亮规则非常有用。

cpp 复制代码
void rehighlight();
void rehighlightBlock(const QTextBlock &block);

3.3 setFormat

setFormat 用于设置匹配到的文本部分的格式,接受字符的起始位置和长度,以及相应的格式对象。

cpp 复制代码
void setFormat(int start, int count, const QTextCharFormat &format);
相关推荐
序属秋秋秋1 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
张璐月2 小时前
mysql join语句、全表扫描 执行优化与访问冷数据对内存命中率的影响
数据库·mysql
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql
quant_19863 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
全干engineer4 小时前
ClickHouse 入门详解:它到底是什么、优缺点、和主流数据库对比、适合哪些场景?
数据库·clickhouse
Hellyc6 小时前
基于模板设计模式开发优惠券推送功能以及对过期优惠卷进行定时清理
java·数据库·设计模式·rocketmq
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
百锦再7 小时前
详细解析 .NET 依赖注入的三种生命周期模式
java·开发语言·.net·di·注入·模式·依赖
风吹落叶花飘荡7 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript