QTextEdit的几种高亮设置(选中文本、关键字)

文本选中区域的颜色可以用 QPalette 或者设置样式表,选中后默认文本是渲染为白色,可以设置 palette 的 brush 为 Qt::NoBrush 保持原本的文本颜色。

    //背景和选区颜色
    QPalette pt = palette();
    pt.setBrush(QPalette::Text, Qt::white);
    pt.setBrush(QPalette::Base, Qt::black);
    pt.setBrush(QPalette::Highlight, Qt::gray);
    pt.setBrush(QPalette::HighlightedText, Qt::NoBrush);
    setPalette(pt);
    //qss貌似没有NoBrush对应的设置
    //setStyleSheet("QTextEdit{color:white;background-color:black;"
    //              "selection-color:white;selection-background-color:gray;}");

关键字语法高亮借助 QSyntaxHighlighter 类,参考官方示例 syntaxhighlighter。

#pragma once
#include <QSyntaxHighlighter>
#include <QTextCharFormat>
#include <QTextDocument>
#include <QRegularExpression>

class MyHighlighter : public QSyntaxHighlighter
{
    Q_OBJECT
public:
    explicit MyHighlighter(QTextDocument *parent = nullptr);

protected:
    void highlightBlock(const QString &text) override;

private:
    struct HighlightingRule
    {
        QRegularExpression pattern;
        QTextCharFormat format;
    };
    QVector<HighlightingRule> highlightingRules;
};

MyHighlighter::MyHighlighter(QTextDocument *parent)
    : QSyntaxHighlighter(parent)
{
    //关键字高亮
    HighlightingRule keys_rule;
    keys_rule.pattern.setPattern("(def|function|return)");
    keys_rule.format.setForeground(QColor(0, 0, 255));
    keys_rule.format.setFontWeight(QFont::Bold);
    highlightingRules.append(keys_rule);

    //双引号范围高亮
    HighlightingRule str_rule;
    str_rule.pattern.setPattern("\".*\"");
    str_rule.format.setForeground(QColor(200, 100, 0));
    str_rule.format.setFontWeight(QFont::Bold);
    highlightingRules.append(str_rule);
}

void MyHighlighter::highlightBlock(const QString &text)
{
    //QRegularExpression
    for (const HighlightingRule &rule : qAsConst(highlightingRules)) {
        QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
        while (matchIterator.hasNext()) {
            QRegularExpressionMatch match = matchIterator.next();
            setFormat(match.capturedStart(), match.capturedLength(), rule.format);
        }
    }
    //QRegExp
    /*for (const HighlightingRule &rule : highlightingRules) {
        QRegExp expression(rule.pattern);
        int index = expression.indexIn(text);
        while (index >= 0) {
            int length = expression.matchedLength();
            setFormat(index, length, rule.format);
            index = expression.indexIn(text, index + length);
        }
    }*/
}
MyHighlighter *keys_lighter = new MyHighlighter(ui->textEdit->document());

当前所在行背景变色,参考官方示例 codeeditor。

    //当前行颜色设置 this派生自QTextEdit
    connect(this, &MyTextEdit::cursorPositionChanged, this, [this](){
        QList<QTextEdit::ExtraSelection> extra_selections;

        QTextEdit::ExtraSelection line;
        line.format.setBackground(QColor(50, 50, 50));
        line.format.setProperty(QTextFormat::FullWidthSelection, true);
        line.cursor = this->textCursor();
        line.cursor.clearSelection();
        extra_selections.append(line);

        this->setExtraSelections(extra_selections);
    });

通过代码选中指定的文本。

    //代码选中指定位置 this派生自QTextEdit
    setPlainText("def function(){\n    print(\"hello qt!\")\n}");
    QString key = "hello";
    /*
    QString text = this->toPlainText();
    int pos = text.indexOf(key);
    if (pos >= 0) {
        QTextCursor cursor = this->textCursor();
        cursor.setPosition(pos, QTextCursor::MoveAnchor); //移到key起始位置
        cursor.movePosition(QTextCursor::NoMove, QTextCursor::KeepAnchor, key.length());
        cursor.select(QTextCursor::WordUnderCursor);
        setTextCursor(cursor);
    }*/
    QTextCursor cursor = this->textCursor();
    QTextDocument *doc = this->document();
    //find有重载,可以指定查找开始的位置
    QTextCursor ret = doc->find(key, cursor, QTextDocument::FindWholeWords);
    if (!ret.isNull()) {
        setTextCursor(ret);
    }

本文测试代码:https://github.com/gongjianbo/MyTestCode/tree/master/Qt/TextEditHighlight

参考博客:https://blog.csdn.net/qq_42351063/article/details/115706359

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龚建波

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值