qt的高亮显示主要是使用qsyntaxhighlighter类,由于qsyntaxhighlighter是抽象基类,所以需要继承并自己实现
//头文件
#ifndef MARKDOWN_HIGHLIGHTER_H
#define MARKDOWN_HIGHLIGHTER_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
class markdown_highlighter : public QSyntaxHighlighter
{
public:
markdown_highlighter(QTextEdit *parent = 0);
void highlightBlock(const QString &text);
void SetColorText(const QString &str, const QColor &color);
void clearRules();
private:
struct HighlightingRule
{
QRegExp pattern;
QTextCharFormat format;
};
QVectorhighlightingRules;
};
#endif // MARKDOWN_HIGHLIGHTER_H
//cpp文件
#include "markdown_highlighter.h"
markdown_highlighter::markdown_highlighter(QTextEdit *parent)
: QSyntaxHighlighter(parent)
{
highlightingRules.clear();
}
void markdown_highlighter::highlightBlock(const QString &text)
{
foreach (HighlightingRule rule, highlightingRules)
{
QRegExp expression(rule.pattern);
int index = text.indexOf(expression);
while (index >= 0)
{
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = text.indexOf(expression, index + length);
}
}
}
void markdown_highlighter::SetColorText(const QString &str, const QColor &color)
{
HighlightingRule rule;
rule.pattern = QRegExp(str);
QTextCharFormat format;
format.setForeground(color);
rule.format = format;
highlightingRules.append(rule);
}
void markdown_highlighter::clearRules()
{
highlightingRules.clear();
}
然后在你需要高亮的地方即可
md_high = new markdown_highlighter(ui->textEdit);
md_high->SetColorText("##",Qt::green);