Using KSyntaxHighlighting in QML
KDE Frameworks provides a syntax highlighting engine with support for more than 300 different configuration, markup and programming languages, known for example for its use in Kate. With KDE Frameworks 5.86 this is now also directly usable from withing QML.
Basic Highlighting
Eike created basic standalone QML bindings for KSyntaxHighlighting some time ago already, which have been used as the basis for what’s now integrated upstream.
If all you need is doing syntax highlighting for a fixed language and using a color theme matching the current system palette this is a matter of just a few lines of code:
import QtQuick.Controls 2.15
import org.kde.syntaxhighlighting 1.0
TextArea {
text: "..."
SyntaxHighlighter {
id: myHighlighter
textEdit: parent
definition: "C++"
}
}
Advanced Use
For more complex uses the syntax definition might not be fixed but depend on input data (e.g.
derived from its mimetype or file name), or a user selection. In the C++ API this is enabled
by the Repository
class, which is now also available in QML as a singleton object.
The following example shows how to use this for a simple syntax selection combo box.
ComboBox {
model: Repository.definitions
displayText: currentValue.translatedName + " (" + currentValue.translatedSection + ")"
textRole: "translatedName"
onCurrentIndexChanged: myHighlighter.definition = currentValue
}
Handling color themes is also possible, similarly to syntax definitions. Themes can be listed, their properties can be accessed and they can be set by theme object or name on the highlighter. Like in the C++ API it’s also possible to just ask for the light or dark default theme.
There’s a QML example
demonstrating all that which can be run with qmlscene
.
KDE Frameworks 6
One of the goals for KDE Frameworks 6 is to have QML bindings directly integrated with the corresponding frameworks themselves. Doing this during the lifetime of 5 allows us to identify issues in the C++ API that we can then adjust in 6 to minimize the need for wrapper or glue code. This reduces maintenance cost and improves usability by making both APIs more similar.
Along those lines there are also QML bindings for KNotification in review.