QT | 关键字高亮

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39419087/article/details/81608990

1、继承QSyntaxHighlighter类,并重写highlightBlock

#ifndef MXSYNTAXHIGHLIGHTER_H
#define MXSYNTAXHIGHLIGHTER_H

#include <QSyntaxhighlighter>


class SyntaxhighlighterC : public QSyntaxHighlighter
{
    Q_OBJECT

public:
    explicit SyntaxhighlighterC(QTextDocument *parent=0);
protected:
    void highlightBlock(const QString &text);//必须重新实现该函数
};
#endif // MXSYNTAXHIGHLIGHTER_H
#include "SyntaxhighlighterC.h"
#include <QTextCharFormat>

SyntaxhighlighterC::SyntaxhighlighterC(QTextDocument *parent):QSyntaxHighlighter(parent)
{

}

void SyntaxhighlighterC::highlightBlock(const QString &text){//高亮文本块
    QTextCharFormat myFormat;//字符格式
    myFormat.setFontWeight(QFont::Bold);
    myFormat.setForeground(Qt::green);
    QString pattern="\\b(auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\\b";
    QRegExp expression(pattern);//创建正则表达式
    int index=text.indexOf(expression);//从位置0开始匹配字符串
    //如果匹配成功,那么返回值为字符串的起始位置,她大于或等于0
    while(index>=0){
        int length=expression.matchedLength();//要匹配字符串的长度
        setFormat(index,length,myFormat);//对要匹配的字符串设置格式
        index=text.indexOf(expression,index+length);//继续匹配
    }
}

2、MainWindow的某个菜单项设置为可选,实现曹函数

/**选择C/C++高亮*/
void MainWindow::on_actionC_C_triggered(bool checked)
{
    if(checked){
        highlighter=new SyntaxhighlighterC(ui->textEdit->document());
    }else{
        highlighter->~QSyntaxHighlighter();//取消高亮
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39419087/article/details/81608990