/*语法高亮 * *包括关键字、函数、注释、@{}、全局变量等等 */ #ifndef MYSYNTAXHIGHLIGHTER_H #define MYSYNTAXHIGHLIGHTER_H #include <QSyntaxHighlighter> #include <QTextCharFormat> //#include <QObject> //#include <QRegExp> #include <QTextEdit> //#include <QVector> //#include <QString> //#include <global_operator.h> QT_BEGIN_NAMESPACE class QTextDocument; QT_END_NAMESPACE class MySyntaxHighlighter:public QSyntaxHighlighter { Q_OBJECT public: MySyntaxHighlighter(QTextDocument *parent = 0); void getKeywords(QString path,QTextEdit* show);//从系统库路径下获取关键字列表,返回信息到消息框 void getFuncwords(QString path,QTextEdit* show);//从用户库目录下获取函数列表,返回信息到消息框 public slots: void setGlobalListQueue(const QStringList& textQueue);//设置全局变量的高亮规则 protected: void highlightBlock(const QString &text) Q_DECL_OVERRIDE; private: struct HighlightingRule { QRegExp pattern; QTextCharFormat format; }; void setNormalTextFormat(); void setDigitalFormat(); void setKeyAndFuncFormat(); void setAtFormat(); void setGlobalFormat(); void setStringFormat(); void setCommentFormat(); // QString kPath;//好像暂时没什么用 // QString fPath; void setGlobalListQueue(); QVector<HighlightingRule> highlightingRules;//其它放在一个矢量里面 QVector<HighlightingRule> globalHighlightRules;//全局变量会时刻变动,不跟其它语法高亮共用一个矢量 QVector<HighlightingRule> atHighlightRules;//艾特的单独存一个矢量里面 //这四个称作其它变量 QTextCharFormat normalTextFormat;//普通文本的样式 QTextCharFormat digitalFormat;//数字样式 QTextCharFormat keywordFormat;//关键字高亮规则 QTextCharFormat functionFormat;//函数高亮 QTextCharFormat globalVarFormat;//全局变量高亮 QTextCharFormat atFormat;//@{}式子高亮 //这s三个不需要矢量 QTextCharFormat commentFormat;//注释高亮 QTextCharFormat multiLineCommentFormat;//块状注释高亮 QTextCharFormat stringFormat;//字符串高亮 //枚举块状注释开始、块状注释结束、单行注释和字符串 enum symbolType{nothing = -1,comBegin = 0,singleCom,aString}; enum symbolType getFirstSymbolTypeOf(QString tContext, int tIndex );//判断tContext中,从tIndex开始,最先出现哪个符号 //如果where在有效区块结束符号*)后面(where>0)或者在previousBlockState=0的行(where=0),则对后面进行一系列检查 void checkFromHere(QString text, int where); //如果区块在where开始,则对后面进行一系列检查 void blockFromHere (QString text, int where); // int startIndex; // int pos; //检查行末的状态 // bool lastCharInSingle = false; // bool lastCharInBlock = false; // bool lastCharInNormal = false;//既不属于字符串又不属于注释 }; #endif // MYSYNTAXHIGHLIGHTER_H
#include <QtGui> #include <QRegExp> #include <QFont> #include <QFile> //#include <algorithm> #include "mysyntaxhighlighter.h" //#include <QDialog> //#include <QMessageBox> //#include <QApplication> //#include <queue&g
Qt Qsyntaxhighlighter给QTextEdit设置丰富的语法高亮格式
最新推荐文章于 2024-07-19 20:06:32 发布
本文介绍如何使用Qt的QSyntaxHighlighter类为QTextEdit创建丰富的语法高亮显示,涵盖关键字、函数、注释、@{}等元素。通过设置不同的格式和规则,实现对代码的智能高亮,提升代码阅读体验。
摘要由CSDN通过智能技术生成