code_edit项目实例06:普通文本/数字/字串高亮显示

新建一个代码高亮类

编写类名

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11
qtHaveModule(printsupport): QT+=printsupport #支持打印

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    mainwindow.cpp \
    myhightlighter.cpp \
    mytextedit.cpp

HEADERS += \
    mainwindow.h \
    myhightlighter.h \
    mytextedit.h

FORMS += \
    mainwindow.ui \
    mytextedit.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

RESOURCES += \
    images.qrc
#ifndef MYHIGHTLIGHTER_H
#define MYHIGHTLIGHTER_H

#include <QObject>
#include <QSyntaxHighlighter>

class MyHightLighter : public QSyntaxHighlighter
{
public:
    explicit MyHightLighter(QTextDocument *parent = nullptr); // explicit避免隐式构造
protected:
    virtual void highlightBlock(const QString &text);
private:
    QString mFontFamily = "Consolas";
    int mFontSize = 14;
    struct HightLightRule {
        QRegExp pattern; // 正则表达式正则表达式
        QTextCharFormat format;
    };
    QVector<HightLightRule> hightLightRules; // 高亮规则
    void AddNormalTextFormat();
    void AddNumberFormat(); // 数字高亮
    void AddStringFormat(); // 字串匹配
};

#endif // MYHIGHTLIGHTER_H
#include "myhightlighter.h"

MyHightLighter::MyHightLighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
    // 对于普通文本
    AddNormalTextFormat();
    // 数字匹配
    AddNumberFormat();
    // 子串匹配
    AddStringFormat();
}

// 普通文本匹配
void MyHightLighter::AddNormalTextFormat()
{
    HightLightRule rule;
    rule.pattern = QRegExp("[a-z0-9A-Z]+"); // 创建正则表达式,+表示重复匹配

    QTextCharFormat normalTextFormat;
    normalTextFormat.setFont(QFont(mFontFamily, mFontSize));
    normalTextFormat.setForeground(QColor(0, 100, 100));
    rule.format = normalTextFormat;
    hightLightRules.append(rule);
}

// 数字匹配
void MyHightLighter::AddNumberFormat()
{
    HightLightRule rule;
    rule.pattern = QRegExp("\\b\\d+|\\d+\\.\\d+\\b"); // 创建正则表达式,+表示重复匹配
    QTextCharFormat numberFormat;
    numberFormat.setFont(QFont(mFontFamily, mFontSize));
    numberFormat.setForeground(QColor(250, 80, 50));
    rule.format = numberFormat;
    hightLightRules.append(rule);
}

// 子串匹配
void MyHightLighter::AddStringFormat()
{

    QTextCharFormat numberFormat;
    numberFormat.setFont(QFont(mFontFamily, mFontSize));
    numberFormat.setForeground(QColor(0, 180, 180));
    HightLightRule rule;
    rule.format = numberFormat;
    // ''
    rule.pattern = QRegExp("'[^']*'"); // 创建正则表达式,+表示重复匹配
    hightLightRules.append(rule);
    // ""
    rule.pattern = QRegExp("\"[^\"]*\"");
    hightLightRules.append(rule);
    //
//    rule.pattern = QRegExp();
//    hightLightRules.append(rule);
}

void MyHightLighter::highlightBlock(const QString &text)
{
    foreach(const HightLightRule &rule, hightLightRules) {
        QRegExp regExp(rule.pattern);
        int index = regExp.indexIn(text);
        while (index >= 0) {
            int length = regExp.matchedLength();
            setFormat(index, length, rule.format); // 匹配字符格式
            index = regExp.indexIn(text, index + length);
        }
    }
}

 

#ifndef MYTEXTEDIT_H
#define MYTEXTEDIT_H

#include <QWidget>

namespace Ui {
class MyTextEdit;
}

class MyTextEdit : public QWidget
{
    Q_OBJECT

public:
    explicit MyTextEdit(QWidget *parent = nullptr);
    ~MyTextEdit();

private slots:
    void textEditHScrollBarChanged();
    void scrollBarChanged();
    void textEditVScrollBarChanged();
    void textBrowerVScrollBarChanged();
    void onTextChanged();
private:
    Ui::MyTextEdit *ui;
    void initConnect();
    void initFont();
    void initHightLighter();
};

#endif // MYTEXTEDIT_H

 

 

#include "myhightlighter.h"
#include "mytextedit.h"
#include "ui_mytextedit.h"
#include <QDebug>

MyTextEdit::MyTextEdit(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyTextEdit)
{
    ui->setupUi(this);
    initConnect();
    initFont();
    // 高亮初始化
    initHightLighter();
}

MyTextEdit::~MyTextEdit()
{
    delete ui;
}

void MyTextEdit::textEditHScrollBarChanged()
{
    qDebug() << "value = " << endl;
    // 将2个滑动条的长度设置成一样
    ui->horizontalScrollBar->setMaximum(ui->textEdit->horizontalScrollBar()->maximum());
    ui->horizontalScrollBar->setMinimum(ui->textEdit->horizontalScrollBar()->minimum());
    ui->horizontalScrollBar->setPageStep(ui->textEdit->horizontalScrollBar()->pageStep());
    ui->horizontalScrollBar->setValue(ui->textEdit->horizontalScrollBar()->value());
}

void MyTextEdit::scrollBarChanged()
{
    ui->textEdit->horizontalScrollBar()->setValue(ui->horizontalScrollBar->value());
}

void MyTextEdit::textEditVScrollBarChanged()
{
    ui->textBrowser->verticalScrollBar()->setValue(ui->textEdit->verticalScrollBar()->value());
}

void MyTextEdit::textBrowerVScrollBarChanged()
{
    ui->textEdit->verticalScrollBar()->setValue(ui->textBrowser->verticalScrollBar()->value());
}

// 绑定信号和槽
void MyTextEdit::initConnect()
{
    connect(ui->textEdit, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
    // 通过信号和槽绑定文本显示框的水平滚动条和自定义水平滚动条
    connect(ui->textEdit->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(textEditHScrollBarChanged()));
    connect(ui->horizontalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarChanged()));
    // 绑定滚动条
    connect(ui->textEdit->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(textEditVScrollBarChanged()));
    connect(ui->textBrowser->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(textBrowerVScrollBarChanged()));
}

// 设置字体
void MyTextEdit::initFont()
{
    QFont font("Consolas", 14);
    ui->textEdit->setFont(font);
    ui->textBrowser->setFont(font);
}

void MyTextEdit::initHightLighter()
{
    new MyHightLighter(ui->textEdit->document());
}

void MyTextEdit::onTextChanged()
{
    int lineCountOfTextEdit = ui->textEdit->document()->lineCount();
    QString text = ui->textBrowser->toPlainText();
    int lineCountOfTextBrowser = text.trimmed().split("\n").length();
    if (lineCountOfTextBrowser > lineCountOfTextEdit) {
        for (int i = lineCountOfTextBrowser; i > lineCountOfTextEdit; i--) {
            text.chop((QString::number(i) + "\n").length());
        }
    } else if (lineCountOfTextBrowser == 1 && text.length() < 1) {
        text += "1\n";
    } else if (lineCountOfTextBrowser < lineCountOfTextEdit) {
        for (int i = lineCountOfTextBrowser; i < lineCountOfTextEdit; ++i) {
            text += QString::number(i + 1) + "\n";
        }
    }
    ui->textBrowser->setMaximumWidth(30 + QString::number(lineCountOfTextEdit).length() * 30);
    ui->textBrowser->setText(text);
}

 

#include "mainwindow.h"

#include <QApplication>
#include "treewidget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值