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);

  • 相关阅读:
    利用Percona monitoring for zabbix监控MySQL
    SQL Server复制故障(1)
    SQL Server事务复制搭建与同步经验
    达梦7入门技术总结--DCA级别
    机器学习:双聚类算法
    脑洞篇之我们生活在9维世界
    自动化运维:使用flask+mysql+highcharts搭建监控平台
    深度学习:Keras入门(二)之卷积神经网络(CNN)
    深度学习:Keras入门(一)之基础篇
    机器学习:特征选择
  • 原文地址:https://www.cnblogs.com/ysherlock/p/7822293.html
Copyright © 2011-2022 走看看