zoukankan      html  css  js  c++  java
  • 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);

  • 相关阅读:
    Java 异常基础详解
    Try-with-resources
    Java集合详解
    Java面向对象之多态
    Java面向对象之继承
    Java面向对象之封装
    Java 接口
    Java抽象类
    Java类和对象
    Java 数组结构
  • 原文地址:https://www.cnblogs.com/ysherlock/p/7822293.html
Copyright © 2011-2022 走看看