qt關鍵字高亮


qt的高亮顯示主要是使用qsyntaxhighlighter類,由於qsyntaxhighlighter是抽象基類,所以需要繼承並自己實現


//頭文件

#ifndef MARKDOWN_HIGHLIGHTER_H
#define MARKDOWN_HIGHLIGHTER_H
 
        
#include <QSyntaxHighlighter>
#include <qtextedit.h>
#include <qtextdocument.h>
#include <QTextCharFormat>
#include <qtextcursor.h>
#include <qhash.h>
#include <qvector.h>
#include <qregexp.h>
#include <qcolor.h>
#include <qstring.h>
 
        
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;
      };
      QVector<HighlightingRule> highlightingRules;
};
 
        
#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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM