Francisco Hernandez Henaine Francisco Hernandez Henaine - 5 months ago 72
C++ Question

How to implement rich text logic on QML TextEdit with QSyntaxHighlighter class in Qt?

I have a TextEdit in my QML file and I have a QSyntaxHighlighter C++ class. I want to specify the highlighting logic in the C++ class and apply it to the TextEdit, but I am not sure how to make the connection between the QML object and the C++ class. Can you also please provide some sample code? I couldn't find how to implement it with the Qt documentation.


In case someone needs a more detailed explanation for this. First, I created a Q_PROPERTY inside a custom C++ class.

Q_PROPERTY(QQuickTextDocument* mainTextEdit READ mainTextEdit WRITE setMainTextEdit NOTIFY mainTextEditChanged)

Then I assign textEdit.textDocument to the Q_PROPERTY in the QML.

customClass.mainTextEdit = textEdit.textDocument

Then I call initHighlighter() (the function has to be Q_INVOKABLE) in my QML which calls the constructor of my highlighter class and passes it the text document of the textEdit.

void initHighlighter()
Highlighter *highlighter;
highlighter = new Highlighter(m_mainTextEdit->textDocument());

Note: The custom highlighter class needs to be derived from QSyntaxHighlighter.