有时候需要用到高亮 QSyntaxHighlighter一个参数为QTextDocument为参数的构造函数:
QSyntaxHighlighter(document)
重写虚函数,以下是官方文档例子,该虚函数当文本块改变时候触发
void MyHighlighter::highlightBlock(const QString &text)
{
QTextCharFormat myClassFormat;
myClassFormat.setFontWeight(QFont::Bold);
myClassFormat.setForeground(Qt::darkMagenta);
QRegularExpression expression("\\bMy[A-Za-z]+\\b");
QRegularExpressionMatchIterator i = expression.globalMatch(text);
while (i.hasNext())
{
QRegularExpressionMatch match = i.next();
setFormat(match.capturedStart(), match.capturedLength(), myClassFormat);
}
}
以下是自己根据上面当函数做当一个事例
#ifndef MYHIGHER_H
#define MYHIGHER_H
#include <QWidget>
#include <QSyntaxHighlighter>
#include <QTextDocument>
class MyHigher : public QSyntaxHighlighter
{
Q_OBJECT
public:
explicit MyHigher(QTextDocument *parent = nullptr);
void highlightBlock(const QString &text);
signals:
public slots:
};
#endif // MYHIGHER_H
#ifndef MYHIGHLIGHTCODER_H
#define MYHIGHLIGHTCODER_H
#include <QWidget>
#include <QPlainTextEdit>
#include "myhigher.h"
class MyHighlightCoder : public QPlainTextEdit
{
Q_OBJECT
public:
explicit MyHighlightCoder(QWidget *parent = nullptr);
signals:
public slots:
private:
MyHigher * higher;
};
#endif // MYHIGHLIGHTCODER_H
#include "myhigher.h"
#include <QSyntaxHighlighter>
#include <QRegularExpression>
#include <QDebug>
MyHigher::MyHigher(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
}
void MyHigher::highlightBlock(const QString &text){
qDebug()<< text;
QTextCharFormat myClassFormat;
myClassFormat.setFontWeight(QFont::Bold);
myClassFormat.setForeground(Qt::blue);
QRegularExpression expression("\\bMy[A-Za-z]+\\b");
QRegularExpressionMatchIterator i = expression.globalMatch(text);
while (i.hasNext())
{
QRegularExpressionMatch match = i.next();
setFormat(match.capturedStart(), match.capturedLength(), myClassFormat);
}
}
#include "myhighlightcoder.h"
MyHighlightCoder::MyHighlightCoder(QWidget *parent) : QPlainTextEdit(parent)
{
QTextDocument * document = this->document();
this->higher = new MyHigher(document);
}
实际会将setFormat方法当执行,也就是改变文本的高亮步奏,通过实际具体的规则进行匹配,不同的类型的关键字配置不通的颜色