使用QSyntaxHighlighter

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是传入高亮显示的文本列表


转载:http://www.cppblog.com/gaimor/archive/2012/04/21/172288.aspx

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值