c++qtsyntax-highlightingqscintilla

Custom syntax highlighting using QScintilla with Qt/C++


I am trying to implement custom syntax highlighting in Qt (C++) using QScintilla, however, the documentation is somehow poor. I googled and only found a tutorial for PyQt (qscintilla.com). I am using C++ not Python.

So where can I start? I have noticed that there is a class QSciLexCustom but it looks really confusing for me.

Actually, my custom syntax is quite similar to C++ and one of the different features is using $ before a variable.


Solution

  • You can subclass QsciLexerCustom and implement a styleText() function:

    class MyCustomLexer: public QsciLexerCustom
    {
    public:
        MyCustomLexer(QsciScintilla *parent);
    
        void styleText(int start, int end);
    
        QString description(int style) const;
        const char *language() const;
    
        QsciScintilla *parent_; 
    };
    
    MyCustomLexer::MyCustomLexer(QsciScintilla *parent)
    {
        setColor(QColor("#000000"), 1);
        setFont(QFont("Consolas", 18), 1);
    }
    
    void MyCustomLexer::styleText(int start, int end)
    {
        QString lexerText = parent_->text(start, end);
        ...
    
        startStyling(...);
        setStyling(..., 1); // set to style 1
    }
    
    QString MyCustomLexer::description(int style) const
    {
        switch (style)
        {
        case 0:
            return tr("Default");   
    ...
    }
    
    const char *MyCustomLexer::language() const
    {
        return "MyCustomLexer";
    }