CopperSpice API  1.7.2
QSyntaxHighlighter Class Referenceabstract

QSyntaxHighlighter class allows syntax highlighting rules to be defined. More...

Inheritance diagram for QSyntaxHighlighter:
QObject

Public Slots

void rehighlight ()
 
void rehighlightBlock (const QTextBlock &block)
 
- Public Slots inherited from QObject
void deleteLater ()
 

Public Methods

 QSyntaxHighlighter (QObject *parent)
 
 QSyntaxHighlighter (QTextDocument *parent)
 
virtual ~QSyntaxHighlighter ()
 
QTextDocumentdocument () const
 
void setDocument (QTextDocument *doc)
 
- Public Methods inherited from QObject
 QObject (QObject *parent=nullptr)
 
 ~QObject ()
 
bool blockSignals (bool block)
 
const QList< QObject * > & children () const
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
void dumpObjectInfo ()
 
void dumpObjectTree ()
 
QList< QStringdynamicPropertyNames () const
 
virtual bool event (QEvent *event)
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
template<typename T >
findChild (const QString &childName=QString ()) const
 
template<class T >
QList< T > findChildren (const QRegularExpression &regExp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
template<class T >
QList< T > findChildren (const QString &objName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
bool inherits (const QString &className) const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const
 
bool isWindowType () const
 
void killTimer (int id)
 
const QMetaObjectmetaObject () const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const
 
QObject * parent () const
 
template<class T = QVariant>
property (const QString &name) const
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const QString &name, const QVariant &value)
 
bool signalsBlocked () const
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 
QThreadthread () const
 

Protected Methods

QTextBlock currentBlock () const
 
int currentBlockState () const
 
QTextBlockUserDatacurrentBlockUserData () const
 
QTextCharFormat format (int pos) const
 
virtual void highlightBlock (const QString &text) = 0
 
int previousBlockState () const
 
void setCurrentBlockState (int newState)
 
void setCurrentBlockUserData (QTextBlockUserData *data)
 
void setFormat (int start, int count, const QColor &color)
 
void setFormat (int start, int count, const QFont &font)
 
void setFormat (int start, int count, const QTextCharFormat &format)
 
- Protected Methods inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signalMethod) const
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signalMethod) const
 
bool isSignalConnected (const QMetaMethod &signalMethod) const
 
int receivers (const QString &signal) const
 
QObject * sender () const
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *event)
 

Additional Inherited Members

- Public Signals inherited from QObject
void destroyed (QObject *obj=nullptr)
 
void objectNameChanged (const QString &objectName)
 
- Static Public Methods inherited from QObject
static bool connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ())
 
static bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...))
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod)
 
static QMetaObjectstaticMetaObject ()
 
static QString tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >())
 
- Properties inherited from QObject
 objectName
 

Detailed Description

The QSyntaxHighlighter class allows syntax highlighting rules to be defined and to query a document's current formatting or user data.

The QSyntaxHighlighter class is a base class for implementing QTextEdit syntax highlighters. A syntax highlighter automatically highlights parts of the text in a QTextEdit, or more generally in a QTextDocument. Syntax highlighters are often used when the user is entering text in a specific format (for example source code) and help the user to read the text and identify syntax errors.

To provide your own syntax highlighting you subclass QSyntaxHighlighter and reimplement highlightBlock(). When you create an instance of your QSyntaxHighlighter subclass pass the QTextEdit or QTextDocument you want the syntax highlighting to be applied to.

Example 1

QTextEdit *editor = new QTextEdit;
MyHighlighter *highlighter = new MyHighlighter(editor->document());

After this your highlightBlock() function will be called automatically whenever necessary. Use your highlightBlock() function to apply formatting (e.g. setting the font and color) to the text that is passed to it. QSyntaxHighlighter provides the setFormat() function which applies a given QTextCharFormat on the current text block. For example:

void MyHighlighter::highlightBlock(const QString &text) {
QTextCharFormat myClassFormat;
myClassFormat.setFontWeight(QFont::Bold);
myClassFormat.setForeground(Qt::darkMagenta);
QString pattern = "\bMy[A-Za-z]+\b";
QRegularExpression expression(pattern);
QRegularExpressionMatch match = expression.match(text);
auto iter = match.capturedStart();
while (iter != text.end()) {
int length = match.capturedLength();
setFormat(index, length, myClassFormat);
iter = expression.match(text, match.capturedEnd());
}
}

Some syntaxes can have constructs that span several text blocks. For example a syntax highlighter should be able to cope with /*...*/ multiline comments. To deal with these cases it is necessary to know the end state of the previous text block.

Inside your highlightBlock() implementation you can query the end state of the previous text block using the previousBlockState() function. After parsing the block you can save the last state using setCurrentBlockState().

The currentBlockState() and previousBlockState() functions return an int value. If no state is set, the returned value is -1. You can designate any other value to identify any given state using the setCurrentBlockState() function. Once the state is set the QTextBlock keeps that value until it is set set again or until the corresponding paragraph of text is deleted.

Example 2

This example uses a state of 1 to signify when the text is "in comment".

The code begins by setting the current block state to 0. Then, if the previous block ended within a comment, we highlight from the beginning of the current block. Otherwise, we search for the given start expression. If the specified end expression can not be found in the text block, the current block state is changed by calling setCurrentBlockState() to make sure the rest of the block is highlighted.

In addition you can query the current formatting and user data using the format() and currentBlockUserData() methods respectively. You can also attach user data to the current text block using the setCurrentBlockUserData() function. QTextBlockUserData can be used to store custom settings. In the case of syntax highlighting it is in particular interesting as cache storage for information you may figure out while parsing the paragraph's text. For an example refer to the setCurrentBlockUserData() documentation.

void MyHighlighter::highlightBlock(const QString &text) {
QTextCharFormat multiLineCommentFormat;
multiLineCommentFormat.setForeground(Qt::red);
QRegularExpression startExpression("/\*");
QRegularExpression endExpression("\*/");
int startIndex = 0;
if (previousBlockState() != 1) {
match = startExpression.match(text);
startIndex = match.capturedStart() - text.begin();
}
while (match.hasMatch()) {
match = endExpression.match(text, match.capturedEnd());
int endIndex = match.capturedStart() - text.begin();
int commentLength;
if (match.hasMatch()) {
commentLength = endIndex - startIndex + match.capturedLength();
} else {
commentLength = text.size() - startIndex;
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
match = startExpression.match(text, match.capturedEnd());
startIndex = match.capturedStart() - text.begin();
}
}
See also
QTextEdit

Constructor & Destructor Documentation

QSyntaxHighlighter::QSyntaxHighlighter ( QObject parent)
explicit

Constructs a QSyntaxHighlighter with the given parent.

QSyntaxHighlighter::QSyntaxHighlighter ( QTextDocument parent)
explicit

Constructs a QSyntaxHighlighter and installs it on parent. The specified QTextDocument also becomes the owner of the QSyntaxHighlighter.

QSyntaxHighlighter::~QSyntaxHighlighter ( )
virtual

Destroys the syntax highlighter and removes it from the text document.

Method Documentation

QTextBlock QSyntaxHighlighter::currentBlock ( ) const
protected

Returns the current text block.

int QSyntaxHighlighter::currentBlockState ( ) const
protected

Returns the state of the current text block. If no value is set, the returned value is -1.

See also
setCurrentBlockState()
QTextBlockUserData * QSyntaxHighlighter::currentBlockUserData ( ) const
protected

Returns the QTextBlockUserData object previously attached to the current text block.

See also
QTextBlock::userData(), setCurrentBlockUserData()
QTextDocument * QSyntaxHighlighter::document ( ) const

Returns the QTextDocument on which this syntax highlighter is installed.

See also
setDocument()
QTextCharFormat QSyntaxHighlighter::format ( int  position) const
protected

Returns the format at position inside the syntax highlighter's current text block.

See also
setFormat()
void QSyntaxHighlighter::highlightBlock ( const QString text)
protectedpure virtual

Highlights the given text block. This method is called when necessary by the text engine on text blocks which have changed.

To provide your own syntax highlighting you must subclass QSyntaxHighlighter and reimplement highlightBlock(). In your reimplementation you should parse the block's text and call setFormat() as often as necessary to apply any font and color changes that you require.

See also
previousBlockState(), setFormat(), setCurrentBlockState()
int QSyntaxHighlighter::previousBlockState ( ) const
protected

Returns the end state of the text block previous to the syntax highlighter's current block. If no value was previously set, the returned value is -1.

See also
highlightBlock(), setCurrentBlockState()
void QSyntaxHighlighter::rehighlight ( )
slot

Reapplies the highlighting to the whole document.

See also
rehighlightBlock()
void QSyntaxHighlighter::rehighlightBlock ( const QTextBlock block)
slot

Reapplies the highlighting to the given QTextBlock block.

See also
rehighlight()
void QSyntaxHighlighter::setCurrentBlockState ( int  newState)
protected

Sets the state of the current text block to newState.

See also
currentBlockState(), highlightBlock()
void QSyntaxHighlighter::setCurrentBlockUserData ( QTextBlockUserData data)
protected

Attaches the given data to the current text block. The ownership is passed to the underlying text document, i.e. the provided QTextBlockUserData object will be deleted if the corresponding text block gets deleted.

QTextBlockUserData can be used to store custom settings. In the case of syntax highlighting, it is in particular interesting as cache storage for information that you may figure out while parsing the paragraph's text.

For example while parsing the text, you can keep track of parenthesis characters that you encounter ('{[(' and the like), and store their relative position and the actual QChar in a simple class derived from QTextBlockUserData:

struct ParenthesisInfo
{
QChar char;
int position;
};
struct BlockData : public QTextBlockUserData
{
};

During cursor navigation in the associated editor, you can ask the current QTextBlock (retrieved using the QTextCursor::block() function) if it has a user data object set and cast it to your BlockData object. Then you can check if the current cursor position matches with a previously recorded parenthesis position, and, depending on the type of parenthesis (opening or closing), find the next opening or closing parenthesis on the same level.

In this way you can do a visual parenthesis matching and highlight from the current cursor position to the matching parenthesis. That makes it easier to spot a missing parenthesis in your code and to find where a corresponding opening/closing parenthesis is when editing parenthesis intensive code.

See also
currentBlockUserData(), QTextBlock::setUserData()
void QSyntaxHighlighter::setDocument ( QTextDocument doc)

Installs the syntax highlighter on the given QTextDocument doc. A QSyntaxHighlighter can only be used with one document at a time.

See also
document()
void QSyntaxHighlighter::setFormat ( int  start,
int  count,
const QColor color 
)
protected

The specified color is applied to the current text block from the start position for a length of count characters.

The other attributes of the current text block, e.g. the font and background color, are reset to default values.

See also
format(), highlightBlock()
void QSyntaxHighlighter::setFormat ( int  start,
int  count,
const QFont font 
)
protected

The specified font is applied to the current text block from the start position for a length of count characters.

The other attributes of the current text block, e.g. the font and background color, are reset to default values.

See also
format(), highlightBlock()
void QSyntaxHighlighter::setFormat ( int  start,
int  count,
const QTextCharFormat format 
)
protected

This function is applied to the syntax highlighter's current text block (i.e. the text that is passed to the highlightBlock() function).

The specified format is applied to the text from the start position for a length of count characters (if count is 0, nothing is done). The formatting properties set in format are merged at display time with the formatting information stored directly in the document, for example as previously set with QTextCursor's functions. Note that the document itself remains unmodified by the format set through this function.

See also
format(), highlightBlock()