本文主要是介绍Qt Qsyntaxhighlighter给QTextEdit设置丰富的语法高亮格式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*语法高亮* *包括关键字、函数、注释、@{}、全局变量等等*/#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_NAMESPACEclass 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设置丰富的语法高亮格式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!