QGIS API Documentation  3.0.2-Girona (307d082)
qgsexpressionhighlighter.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsexpressionhighlighter.cpp - A syntax highlighter for a qgsexpression
3  --------------------------------------
4  Date : 28-Dec-2011
5  Copyright : (C) 2011 by Nathan Woodrow
6  Email : woodrow.nathan at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
17 
19  : QSyntaxHighlighter( parent )
20 {
21  HighlightingRule rule;
22 
23  keywordFormat.setForeground( Qt::darkBlue );
24  keywordFormat.setFontWeight( QFont::Bold );
25  QStringList keywordPatterns;
26  keywordPatterns << QStringLiteral( "\\bCASE\\b" ) << QStringLiteral( "\\bWHEN\\b" ) << QStringLiteral( "\\bTHEN\\b" )
27  << QStringLiteral( "\\bELSE\\b" ) << QStringLiteral( "\\bEND\\b" );
28 
29  Q_FOREACH ( const QString &pattern, keywordPatterns )
30  {
31  rule.pattern = QRegExp( pattern, Qt::CaseInsensitive );
32  rule.format = keywordFormat;
33  highlightingRules.append( rule );
34  }
35 
36  quotationFormat.setForeground( Qt::darkGreen );
37  rule.pattern = QRegExp( "\'[^\'\r\n]*\'" );
38  rule.format = quotationFormat;
39  highlightingRules.append( rule );
40 
41  columnNameFormat.setForeground( Qt::darkRed );
42  rule.pattern = QRegExp( "\"[^\"\r\n]*\"" );
43  rule.format = columnNameFormat;
44  highlightingRules.append( rule );
45 }
46 
47 void QgsExpressionHighlighter::addFields( const QStringList &fieldList )
48 {
49  columnNameFormat.setForeground( Qt::darkRed );
50  HighlightingRule rule;
51  Q_FOREACH ( const QString &field, fieldList )
52  {
53  if ( field.isEmpty() ) // this really happened :)
54  continue;
55  rule.pattern = QRegExp( "\\b" + field + "\\b" );
56  rule.format = columnNameFormat;
57  highlightingRules.append( rule );
58  }
59 }
60 
61 void QgsExpressionHighlighter::highlightBlock( const QString &text )
62 {
63  Q_FOREACH ( const HighlightingRule &rule, highlightingRules )
64  {
65  QRegExp expression( rule.pattern );
66  int index = expression.indexIn( text );
67  while ( index >= 0 )
68  {
69  int length = expression.matchedLength();
70  if ( length == 0 )
71  break; // avoid infinite loops
72  setFormat( index, length, rule.format );
73  index = expression.indexIn( text, index + length );
74  }
75  }
76 }
77 
void highlightBlock(const QString &text) override
QgsExpressionHighlighter(QTextDocument *parent=nullptr)
void addFields(const QStringList &fieldList)