QT系列教程(11) TextEdit实现Qt 文本高亮

文本高亮

对于textedit里录入的部分单词我们可以实现高亮,实现高亮主要依赖于QSyntaxHighlighter。
我们先创建一个Qt Application类,类名MainWindow, 然后新增一个C++类,类名为MySyntaxHighlighter。

#ifndef MYSYNTAXHIGHLIGHTER_H
#define MYSYNTAXHIGHLIGHTER_H
#include <QSyntaxHighlighter>
#include <QTextDocument>
class MySyntaxHighlighter:public QSyntaxHighlighter
{
    Q_OBJECT
public:
    explicit MySyntaxHighlighter(QTextDocument* parent = 0);
    //重写实现高亮
protected:
    void highlightBlock(const QString& text);
};

#endif // MYSYNTAXHIGHLIGHTER_H

这个类声明了highlightBlock函数,这是一个虚函数继承自QSyntaxHighlighter。每次我们录入文字时,会自动调用这个函数。下面实现MySyntaxHighlighter类

#include "mysyntaxhighlighter.h"
#include <QFont>

MySyntaxHighlighter::MySyntaxHighlighter(QTextDocument* parent):QSyntaxHighlighter (parent)
{

}

void MySyntaxHighlighter::highlightBlock(const QString &text)
{
    QTextCharFormat myFormat;
    myFormat.setFont(QFont("微软雅黑"));
    myFormat.setFontWeight(QFont::Bold);
    myFormat.setForeground(Qt::green);
    //匹配char
    QString pattern = "\\bchar\\b";
    //创建正则表达式
    QRegExp express(pattern);
    //从索引0的位置开始匹配
    int index = text.indexOf(express);
    while (index>0) {
        int matchLen = express.matchedLength();
        //对匹配的字符串设置高亮
        setFormat(index, matchLen, myFormat);
        index = text.indexOf(express, index+matchLen);
    }
}

在highlightBlock函数中,我们实现了一个高亮的文字模式,当录入的字符串包含char时,char会被高亮。
我们在mainwindow.ui中添加一个textedit,然后在mainwindow的构造函数中添加我们刚才编写的高亮模块。

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_ligher = new MySyntaxHighlighter(ui->textEdit->document());
}

程序运行后,在编辑器中输入hello char,会看到char高亮了
https://cdn.llfc.club/1665137215851.jpg

实现代码编辑器

Qt 的案例中有提供过文本高亮和显示行号的demo,我把它整理起来了。
我们先声明codeeditor类,以及行号显示的类

#ifndef CODEEDITOR_H
#define CODEEDITOR_H

#include <QPlainTextEdit>

QT_BEGIN_NAMESPACE
class QPaintEvent;
class QResizeEvent;
class QSize;
class QWidget;
QT_END_NAMESPACE

class LineNumberArea;

class CodeEditor : public QPlainTextEdit
{
    Q_OBJECT

public:
    CodeEditor(QWidget *parent = nullptr);

    void lineNumberAreaPaintEvent(QPaintEvent *event);
    int lineNumberAreaWidth();

protected:
    void resizeEvent(QResizeEvent *event) override;

private slots:
    void updateLineNumberAreaWidth(int newBlockCount);
    void highlightCurrentLine();
    void updateLineNumberArea(const QRect &rect, int dy);

private:
    QWidget *lineNumberArea;
};

class LineNumberArea : public QWidget
{
public:
    LineNumberArea(CodeEditor *editor) : QWidget(editor), codeEditor(editor)
    {}

    QSize sizeHint() const override
    {
        return QSize(codeEditor->lineNumberAreaWidth(), 0);
    }

protected:
    void paintEvent(QPaintEvent *event) override
    {
        codeEditor->lineNumberAreaPaintEvent(event);
    }

private:
    CodeEditor *codeEditor;
};

#endif

具体代码类的实现

#include "codeeditor.h"

#include <QPainter>
#include <QTextBlock>

CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)
{
    lineNumberArea = new LineNumberArea(this);

    connect(this, &CodeEditor::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth);
    connect(this, &CodeEditor::updateRequest, this, &CodeEditor::updateLineNumberArea);
    connect(this, &CodeEditor::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine);

    updateLineNumberAreaWidth(0);
    highlightCurrentLine();
}

int CodeEditor::lineNumberAreaWidth()
{
    int digits = 1;
    int max = qMax(1, blockCount());
    while (max >= 10) {
        max /= 10;
        ++digits;
    }

    int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;

    return space;
}

void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
    setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}

void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
    if (dy)
        lineNumberArea->scroll(0, dy);
    else
        lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());

    if (rect.contains(viewport()->rect()))
        updateLineNumberAreaWidth(0);
}

void CodeEditor::resizeEvent(QResizeEvent *e)
{
    QPlainTextEdit::resizeEvent(e);

    QRect cr = contentsRect();
    lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}

void CodeEditor::highlightCurrentLine()
{
    QList<QTextEdit::ExtraSelection> extraSelections;

    if (!isReadOnly()) {
        QTextEdit::ExtraSelection selection;

        QColor lineColor = QColor(Qt::yellow).lighter(160);

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extraSelections.append(selection);
    }

    setExtraSelections(extraSelections);
}

void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
    QPainter painter(lineNumberArea);
    painter.fillRect(event->rect(), Qt::lightGray);

    QTextBlock block = firstVisibleBlock();
    int blockNumber = block.blockNumber();
    int top = qRound(blockBoundingGeometry(block).translated(contentOffset()).top());
    int bottom = top + qRound(blockBoundingRect(block).height());

    while (block.isValid() && top <= event->rect().bottom()) {
        if (block.isVisible() && bottom >= event->rect().top()) {
            QString number = QString::number(blockNumber + 1);
            painter.setPen(Qt::black);
            painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
                             Qt::AlignHCenter, number);
        }

        block = block.next();
        top = bottom;
        bottom = top + qRound(blockBoundingRect(block).height());
        ++blockNumber;
    }
}

上面实现了代码编辑器的行号和当前行黄色高亮显示。
接下来实现高亮显示类

#ifndef HIGHLIGHTER_H
#define HIGHLIGHTER_H

#include <QSyntaxHighlighter>
#include <QTextCharFormat>
#include <QRegularExpression>

QT_BEGIN_NAMESPACE
class QTextDocument;
QT_END_NAMESPACE

//! [0]
class Highlighter : public QSyntaxHighlighter
{
    Q_OBJECT

public:
    Highlighter(QTextDocument *parent = 0);

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

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

    QRegularExpression commentStartExpression;
    QRegularExpression commentEndExpression;

    QTextCharFormat keywordFormat;
    QTextCharFormat classFormat;
    QTextCharFormat singleLineCommentFormat;
    QTextCharFormat multiLineCommentFormat;
    QTextCharFormat quotationFormat;
    QTextCharFormat functionFormat;
};
//! [0]

#endif // HIGHLIGHTER_H

具体实现细节如下,先定义高亮的正则规则,然后在highlightBlock函数里根据规则点亮不同的单词

#include "highlighter.h"

//! [0]
Highlighter::Highlighter(QTextDocument *parent)
    : QSyntaxHighlighter(parent)
{
    HighlightingRule rule;

    keywordFormat.setForeground(Qt::darkBlue);
    keywordFormat.setFontWeight(QFont::Bold);
    const QString keywordPatterns[] = {
        QStringLiteral("\\bchar\\b"), QStringLiteral("\\bclass\\b"), QStringLiteral("\\bconst\\b"),
        QStringLiteral("\\bdouble\\b"), QStringLiteral("\\benum\\b"), QStringLiteral("\\bexplicit\\b"),
        QStringLiteral("\\bfriend\\b"), QStringLiteral("\\binline\\b"), QStringLiteral("\\bint\\b"),
        QStringLiteral("\\blong\\b"), QStringLiteral("\\bnamespace\\b"), QStringLiteral("\\boperator\\b"),
        QStringLiteral("\\bprivate\\b"), QStringLiteral("\\bprotected\\b"), QStringLiteral("\\bpublic\\b"),
        QStringLiteral("\\bshort\\b"), QStringLiteral("\\bsignals\\b"), QStringLiteral("\\bsigned\\b"),
        QStringLiteral("\\bslots\\b"), QStringLiteral("\\bstatic\\b"), QStringLiteral("\\bstruct\\b"),
        QStringLiteral("\\btemplate\\b"), QStringLiteral("\\btypedef\\b"), QStringLiteral("\\btypename\\b"),
        QStringLiteral("\\bunion\\b"), QStringLiteral("\\bunsigned\\b"), QStringLiteral("\\bvirtual\\b"),
        QStringLiteral("\\bvoid\\b"), QStringLiteral("\\bvolatile\\b"), QStringLiteral("\\bbool\\b")
    };
    for (const QString &pattern : keywordPatterns) {
        rule.pattern = QRegularExpression(pattern);
        rule.format = keywordFormat;
        highlightingRules.append(rule);
//! [0] //! [1]
    }
//! [1]

//! [2]
    classFormat.setFontWeight(QFont::Bold);
    classFormat.setForeground(Qt::darkMagenta);
    rule.pattern = QRegularExpression(QStringLiteral("\\bQ[A-Za-z]+\\b"));
    rule.format = classFormat;
    highlightingRules.append(rule);
//! [2]

//! [3]
    singleLineCommentFormat.setForeground(Qt::red);
    rule.pattern = QRegularExpression(QStringLiteral("//[^\n]*"));
    rule.format = singleLineCommentFormat;
    highlightingRules.append(rule);

    multiLineCommentFormat.setForeground(Qt::red);
//! [3]

//! [4]
    quotationFormat.setForeground(Qt::darkGreen);
    rule.pattern = QRegularExpression(QStringLiteral("\".*\""));
    rule.format = quotationFormat;
    highlightingRules.append(rule);
//! [4]

//! [5]
    functionFormat.setFontItalic(true);
    functionFormat.setForeground(Qt::blue);
    rule.pattern = QRegularExpression(QStringLiteral("\\b[A-Za-z0-9_]+(?=\\()"));
    rule.format = functionFormat;
    highlightingRules.append(rule);
//! [5]

//! [6]
    commentStartExpression = QRegularExpression(QStringLiteral(" /\\*"));
    commentEndExpression = QRegularExpression(QStringLiteral("\\*/"));
}
//! [6]

//! [7]
void Highlighter::highlightBlock(const QString &text)
{
    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);
        }
    }
//! [7] //! [8]
    setCurrentBlockState(0);
//! [8]

//! [9]
    int startIndex = 0;
    if (previousBlockState() != 1)
        startIndex = text.indexOf(commentStartExpression);

//! [9] //! [10]
    while (startIndex >= 0) {
//! [10] //! [11]
        QRegularExpressionMatch match = commentEndExpression.match(text, startIndex);
        int endIndex = match.capturedStart();
        int commentLength = 0;
        if (endIndex == -1) {
            setCurrentBlockState(1);
            commentLength = text.length() - startIndex;
        } else {
            commentLength = endIndex - startIndex
                            + match.capturedLength();
        }
        setFormat(startIndex, commentLength, multiLineCommentFormat);
        startIndex = text.indexOf(commentStartExpression, startIndex + commentLength);
    }
}
//! [11]

接下来在MainWindow里添加editor

void MainWindow::setupEditor()
{
    QFont font;
    font.setFamily("Courier");
    font.setFixedPitch(true);
    font.setPointSize(10);

    editor = new CodeEditor();
    editor->setFont(font);

    highlighter = new Highlighter(editor->document());

    QFile file("mainwindow.h");
    if (file.open(QFile::ReadOnly | QFile::Text))
        editor->setPlainText(file.readAll());
}

运行程序后,输入部分代码显示如下
https://cdn.llfc.club/1665137935233.jpg
具体细节大家可以参考代码理解即可。

总结

源码链接https://gitee.com/secondtonone1/qt-learning-notes

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/713241.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

优化查询性能:DolphinDB 时间类型数据比较规则详解

在数据库中&#xff0c;时间是一种常见的数据类型。在处理时间数据时&#xff0c;比较操作是非常常见的需求。然而&#xff0c;在不同的场景下&#xff0c;对时间类型数据进行比较时应用的规则不同。本文将从 DolphinDB 支持的时间类型开始&#xff0c;由浅入深分别介绍时间类型…

C++访问Private,Protecd的一些方法总结

前言 在编写C程序中 我们偶尔会碰到这样的三种特殊修改变量值的需求&#xff1a; [1]在不修改类原本的实现下&#xff0c;访问修改类的Private变量 [2]在不修改类原本的实现下&#xff0c;修改类的Protected变量 Private变量访问 public类模版函数特化 这种办法利用了类模…

Qt自定义日志输出

Qt自定义日志输出 简略版&#xff1a; #include <QApplication> #include <QDebug> #include <QDateTime> #include <QFileInfo> // 将日志类型转换为字符串 QString typeToString(QtMsgType type) {switch (type) {case QtDebugMsg: return "D…

全网爆火的AI语音合成工具-ChatTTS,有人已经拿它赚到了第一桶金,送增强版整合包

上篇分享了如何从0到1搭建一套语音交互系统。 其中&#xff0c;语音合成&#xff08;TTS&#xff09;是提升用户体验的关键所在。 不得不说&#xff0c;AI 语音界人才辈出&#xff0c;从之前的Bert-Sovit&#xff0c;到GPT-Sovits&#xff0c;再到最近一周狂揽了 1w Star 的C…

热门开源项目ChatTTS: 国内语音技术突破,实现弯道超车

✨✨ 欢迎大家来访Srlua的博文&#xff08;づ&#xffe3;3&#xffe3;&#xff09;づ╭❤&#xff5e;✨✨ &#x1f31f;&#x1f31f; 欢迎各位亲爱的读者&#xff0c;感谢你们抽出宝贵的时间来阅读我的文章。 我是Srlua小谢&#xff0c;在这里我会分享我的知识和经验。&am…

细说MCU修改回调函数调用模式的方法

目录 1、硬件及工程 2、实现方法 &#xff08;1&#xff09;修改while(1)中的代码&#xff1a; &#xff08;2&#xff09;修改2 &#xff08;3&#xff09;修改3 &#xff08;4&#xff09;修改4 &#xff08;5&#xff09;修改5 3、下载并运行 在本文作者的文章中&a…

RPC知识

一、为什么要有RPC&#xff1a; HTTP协议的接口&#xff0c;在接口不多、系统与系统交互较少的情况下&#xff0c;解决信息孤岛初期常使用的一种通信手段&#xff1b;优点就是简单、直接、开发方便&#xff0c;利用现成的HTTP协议进行传输。 但是&#xff0c;如果是一个大型的网…

python-基础篇-函数-在py中的长相

文章目录 整体长相长相要求 整体长相 怎么自定义函数&#xff1f; 要知道怎么定义函数&#xff0c;就要知道函数的组成部分是怎样的。 def 函数名(参数1&#xff0c;参数2....参数n):函数体return 语句这就是 Python 函数的组成部分。 长相要求 所以自定义函数&#xff0c…

读AI新生:破解人机共存密码笔记02进化

1. 人工智能的标准模型 1.1. 机器优化人类提供的固定目标 1.1.1. 是一条死胡同 1.1.1.1. 当你走进死胡同时&#xff0c;你最好掉头返回&#xff0c;找出走错的地方 1.2. 问题不在于我们可能无法做好构建人工智能系统的工作&…

【loguru】【notifiers】配置ERROR级别邮件发送通知

完整代码 from loguru import logger from notifiers import get_notifier# 获取电子邮件通知器 notifier get_notifier("email")# 配置电子邮件通知参数 email_params {"username": "xxxxx163.com", # 发送邮件的用户名&#xff0c;我这里用…

时机:产品成功的关键因子

在商业世界里&#xff0c;产品成功与否往往与许多因素有关&#xff1a;优秀的创意、强大的团队、充足的资金等。然而&#xff0c;在这些因素之外&#xff0c;一个常被忽视但至关重要的因素就是“时机”。正如古语所言&#xff1a;“人为可做&#xff0c;天时难造”&#xff0c;…

LabVIEW电子类实验虚拟仿真系统

开发了基于LabVIEW开发的电子类实验虚拟仿真实验系统。该系统通过图形化编程方式&#xff0c;实现了复杂电子实验操作的虚拟化&#xff0c;不仅提高了学生的操作熟练度和学习兴趣&#xff0c;而且通过智能评价模块提供即时反馈&#xff0c;促进教学和学习的互动。 项目背景 在…

目标检测——可见光和红外船舶图像配对数据集

引言 亲爱的读者们&#xff0c;您是否在寻找某个特定的数据集&#xff0c;用于研究或项目实践&#xff1f;欢迎您在评论区留言&#xff0c;或者通过公众号私信告诉我&#xff0c;您想要的数据集的类型主题。小编会竭尽全力为您寻找&#xff0c;并在找到后第一时间与您分享。 …

webpack逆向

声明&#xff1a;个人总结记录一下&#xff0c;避免忘记 1、webpack 类型 单文件 直接可以在文件顶部找到加载器 多文件 顶部找不到加载器 如图所示 多文件的这话&#xff0c;全局搜所 69725 找到类似n(69725) ,单点n进去&#xff0c;可以找到加载器 2、调用 通过赋值的方…

金属3D打印技术革新模具制造业

在当今竞争激烈的制造业领域&#xff0c;模具制造业正面临着诸多挑战。冷却时间长、模具温度控制困难、制造周期长以及成本高昂等问题&#xff0c;一直是制约模具制造业发展的瓶颈。然而&#xff0c;随着金属3D打印技术的快速发展&#xff0c;模具制造业迎来了前所未有的机遇。…

SpringAI快速上手

一、导入依赖 镜像&#xff08;导入maven依赖&#xff09; <repositories><repository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><releases><enabled>…

宿舍用电管理模块一进三出的升级改造

宿舍用电管理模块一进三出石家庄光大远通电气有限公司产品在高校日常管理工作中,宿舍管理是一项重要工作。宿舍管理内容复杂,而且涉及学生的日常生活,意义重大。其中,学生宿舍内漏电,超负荷用电,违规用电等现象一直是困扰后勤管理的普遍问题。随着学生日常生活方式以及生活用品…

光功率计传感器

光探测仪表: 激光功率计探头按照不同的原理和材料分为热电堆型、光电二极管型以及包含两种传感器的综合探头, 激光能量计则有热释电传感器和热电堆传感器探头 热释电效应传感器: 热释电传感器的工作原理主要是基于热释电效应。当物体处于不同温度时,会发射出不同强度的红…

【RabbitMQ】异步消息及Rabbitmq安装

https://blog.csdn.net/weixin_73077810/article/details/133836287 https://www.bilibili.com/video/BV1mN4y1Z7t9/ 同步调用和异步调用 如果我们的业务需要实时得到服务提供方的响应&#xff0c;则应该选择同步通讯&#xff08;同步调用&#xff09;。 如果我们追求更高的效…

怎样快速清理电脑里的所有软件 怎么删除干净电脑软件

苹果电脑内的软件来源主要有两个&#xff0c;一是系统预装&#xff0c;二是用户自行下载。但并不是所有应用程序都是高频使用状态&#xff0c;甚至好多是从未打开过的“屏幕装饰”。小编今日独家攻略&#xff0c;内存告急如何快速清理电脑里的所有软件&#xff0c;怎么删除干净…