QT中QSyntaxHighlighter主要和QTextEdit配合使用,高亮显示关键字
一个简单的例子如下:
#ifndef HIGHLIGHTER_H
#define HIGHLIGHTER_H
#include <QSyntaxHighlighter>
#include <QTextCharFormat>
QT_BEGIN_NAMESPACE
class QTextDocument;
QT_END_NAMESPACE
class Highlighter : public QSyntaxHighlighter
{
Q_OBJECT
public:
Highlighter(QTextDocument *parent = 0);
public slots:
void setTextQueue(const QStringList& textQueue);
protected:
void highlightBlock(const QString &text);
private:
struct HighlightingRule
{
QRegExp pattern;
QTextCharFormat format;
};
QVector<HighlightingRule> highlightingRules;
QTextCharFormat keywordFormat;
};
#endif
.cpp
#include <QtGui>
#include "highlighter.h"
Highlighter::Highlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
keywordFormat.setForeground(Qt::darkRed);
keywordFormat.setFontWeight(QFont::Bold);
}
void Highlighter::highlightBlock(const QString &text)
{
foreach(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);
}
}
setCurrentBlockState(0);
}
void Highlighter::setTextQueue(const QStringList& textQueue)
{
highlightingRules.clear();
HighlightingRule rule;
const QString tmp("\\b");
foreach(const QString& str,textQueue)
{
QString pattern(tmp);
pattern += str;
pattern += tmp;
rule.pattern = QRegExp(pattern);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
}
在这里setTextQueue是传入高亮显示的文本列表