Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
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是传入高亮显示的文本列表
posted on 2012-04-21 22:59 ccsdu2009 阅读(2804) 评论(0)  编辑 收藏 引用 所属分类: QT编程

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理