CopperSpice API  1.9.1
QSyntaxHighlighter Class Referenceabstract

QSyntaxHighlighter class provides a mechanism for defining highlighting rules. 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 &childName=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 position) 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)
 
static bool disconnect (const QObject *sender, std::nullptr_t, const QObject *receiver, std::nullptr_t)
 
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 provides a mechanism for defining highlighting rules. This abstract class was designed to be used as a base class in a user application. To implement syntax highlighting inherit from QSyntaxHighlighter and implement the virtual highlightBlock() method. In the constructor of your new class, pass a pointer to the QTextDocument which contains the text to be highlighted.

Example 1

In this example a new class called MySyntax is declared which must inherit from QSyntaxHighlighter and override the highlightBlock() method.

class MySyntax : public QSyntaxHighlighter
{
CS_OBJECT(MySyntax)
public:
MySyntax(QTextDocument *document);
protected:
void highlightBlock(const QString &text) override;
};

The highlightBlock() method contains the rules to configure the font and coloring for a given word located in the text. This method must call the base class method setFormat() to actually apply the formatting changes.

void MySyntax::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());
}
}

To use the MySyntax class for highlighting create a widget like a QTextEdit or QPlainTextEdit. The widget data type must be able to return a pointer to a QTextDocument.

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

Multi Line Highlighting

There are cases where highlighting will need to span multiple text blocks. An example would be a multiline comment in C++. This requires the syntax highlighter to store the end state of the previous text block. The end state of the previous text block can be retrieved by calling previousBlockState(). After parsing the block save the last state using setCurrentBlockState().

The currentBlockState() and previousBlockState() methods return an integer value. If no state is set the returned value is -1. Other values can be used to indicate other states using the setCurrentBlockState() method. Once the state is set the QTextBlock retains this value until it is set again or until the corresponding paragraph of text is deleted.

Example 2

The following example uses a block value of 1 to signify when the given text is part of a comment.

The code begins by setting the current block state to 0. If the previous block of text ended within a comment the text is highlighted from the beginning of the current block. Otherwise, a search is done to find out if a comment starts in the current block.

If the current block ends inside a comment, the block state is changed from 0 to 1 by calling setCurrentBlockState() so the following block can be highlighted.

There are two other methods which can be called to query the current formatting and user data. The are format() and currentBlockUserData().

The setCurrentBlockUserData() method can be used to associate user data with the current text block. QTextBlockUserData can be used to store custom settings.

void MySyntax::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 associates it with parent document. The given parent 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 this syntax highlighter is associated with.

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 by the text engine when text blocks are changed.

To provide a custom syntax highlighting inherit from QSyntaxHighlighter and reimplement highlightBlock(). In your reimplementation parse the text and call setFormat() as often as necessary to apply any required font and color changes.

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

Runs the highlighting process on the entire document.

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

Runs the highlighting process on the given 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 which means the QTextBlockUserData object will be deleted if the corresponding text block is deleted.

QTextBlockUserData can be used to store custom settings. With syntax highlighting, this data can be used as cache storage. For example, while parsing the text you can keep track of parenthesis characters like '{[(' and store their relative position and the actual QChar in a class which inherits from QTextBlockUserData.

struct ParenthesisInfo
{
QChar char;
int position;
};
struct BlockData : public QTextBlockUserData
{
};
See also
currentBlockUserData(), QTextBlock::setUserData()
void QSyntaxHighlighter::setDocument ( QTextDocument doc)

Installs the syntax highlighter on the given 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 like 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 like 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 method is applied to the syntax highlighter's current text block.

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 the QTextCursor methods. The document itself remains unmodified by the format set through this method.

See also
format(), highlightBlock()