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

  • 相关阅读:
    HTML知识点链接
    Apache和PHP的安装
    MySql的安装
    MY_FIRSH_MODULE
    【PAT甲级】1053 Path of Equal Weight (30 分)(DFS)
    Atcoder Grand Contest 039B(思维,BFS)
    Codeforces Round #589 (Div. 2)E(组合数,容斥原理,更高复杂度做法为DP)
    Codeforces Round #589 (Div. 2)D(思维,构造)
    【PAT甲级】1052 Linked List Sorting (25 分)
    【PAT甲级】1051 Pop Sequence (25 分)(栈的模拟)
  • 原文地址:https://www.cnblogs.com/ysherlock/p/7822293.html
Copyright © 2011-2022 走看看