You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt文本编辑器高亮指定关键词时程序崩溃的问题排查

问题分析与解决方案

你的代码出现死循环,导致程序最终崩溃。原因是每次找到关键词后,QTextDocument::find会返回一个选中该关键词的光标,而你直接将这个光标作为下一次查找的起始位置,这会导致find重复定位到同一个关键词,进入无限循环,最终引发段错误。你观察到的“循环内前序代码重复执行多次”正是死循环的表现。


修复后的手动高亮代码

修复方案很简单,每次处理完一个关键词后,将光标移动到选中文本的末尾,确保下一次查找从当前关键词之后开始:

void objectDetector::highlightKeywords()
{
    QString text = ui->textEdit->toPlainText();

    // 关键词列表
    QStringList keywords;
    keywords << "red" << "bold";

    // 定义高亮格式
    QTextCharFormat keywordFormat;
    keywordFormat.setForeground(Qt::red);
    keywordFormat.setFontWeight(QFont::Bold);

    // 遍历每个关键词
    for (const QString& keyword : keywords) {
        QTextDocument* document = ui->textEdit->document();
        QTextCursor cursor(document);

        // 循环查找所有匹配项
        cursor = document->find(keyword, cursor, QTextDocument::FindWholeWords);
        while (!cursor.isNull()) {
            // 应用高亮格式
            cursor.mergeCharFormat(keywordFormat);
            // 将光标移动到当前匹配项的末尾,避免重复查找
            cursor.setPosition(cursor.selectionEnd());
            // 查找下一个匹配项
            cursor = document->find(keyword, cursor, QTextDocument::FindWholeWords);
        }
    }
}

更优方案:使用QSyntaxHighlighter

Qt官方推荐使用QSyntaxHighlighter类实现语法高亮,这是专门为这类场景设计的组件,代码更简洁、性能更优,还能自动处理文本编辑时的实时高亮,彻底避免手动操作光标可能出现的错误。

1. 创建自定义高亮器类

#include <QSyntaxHighlighter>
#include <QRegularExpression>

class KeywordHighlighter : public QSyntaxHighlighter
{
    Q_OBJECT
public:
    explicit KeywordHighlighter(QTextDocument *parent = nullptr)
        : QSyntaxHighlighter(parent)
    {
        // 配置关键词高亮格式
        QTextCharFormat keywordFormat;
        keywordFormat.setForeground(Qt::red);
        keywordFormat.setFontWeight(QFont::Bold);

        // 添加高亮规则(匹配整个单词)
        HighlightingRule rule;
        rule.pattern = QRegularExpression(R"(\b(red|bold)\b)");
        rule.format = keywordFormat;
        highlightingRules.append(rule);
    }

protected:
    void highlightBlock(const QString &text) override
    {
        // 应用所有高亮规则
        for (const HighlightingRule &rule : qAsConst(highlightingRules)) {
            QRegularExpressionMatchIterator matchIter = rule.pattern.globalMatch(text);
            while (matchIter.hasNext()) {
                QRegularExpressionMatch match = matchIter.next();
                setFormat(match.capturedStart(), match.capturedLength(), rule.format);
            }
        }
    }

private:
    struct HighlightingRule
    {
        QRegularExpression pattern;
        QTextCharFormat format;
    };

    QList<HighlightingRule> highlightingRules;
};

2. 在编辑器初始化时绑定高亮器

// 例如在窗口类构造函数中执行
ui->textEdit->setDocument(new QTextDocument(this));
new KeywordHighlighter(ui->textEdit->document());

这样无需手动调用highlightKeywords函数,Qt会自动在文本变化时处理高亮。

内容的提问来源于stack exchange,提问作者Lookdatway

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:07:06