"Smart" content for TextDocument with C++, QTextDocument, and QML TextEdit
-
context: I'm getting back into Qt after a very long time away because I'm working on an experimental hobby project that requires fine control of the document model behind a rich text editor: QML and Quick controls meet other requirements, like running on mobile devices and looking good.
what I want: To connect a QML TextEdit to some C++ code that can automatically update the document, similar to
QSyntaxHighlighter
.what I've got: Something that basically works, which is great, but won't scale well. The documentation says I'm not allowed to change
TextEdit::textDocument::textDocument
directly, so I connectQTextDocument::contentChanged
to a slot that copies and revises into a newQTextDocument
before publishingtoHtml()
as the value of a property that is passed toTextEdit::setRichText()
.what's wrong: Creating a new
QTextDocument
and replacing the existing doc with an HTML representation a slightly different version of that doc, well, it just feels not-quite-right.question: Is there a more sensible way to do this? Is it any different from the way
QSyntaxHighlighter
should to be used with QML'sTextEdit
in order to have syntax highlighting while the user is editing the text? -
Aha! Given a
TextEdit
namedtextEdit
, I can insert Qt's rich text HTML subset throughtextEdit.insert
. In combination withtextEdit.remove
, effectively replacing existing text with re-formatted text. This is a (minimal) answer to my own question.Unfortunately, since I can't use a
QTextCursor::beginEditBlock
andendEditBlock
with this solution, I can't prevent theremove
+insert
from adding two items to theQTextDocument
's "undo" history. That's a bit messy, but I can live with it if I know I'll be able to fix it later - whether by being able to replace a document fragment in a single undoable op, or by overriding the built-in "undo/redo" feature with my own.I appreciate how the simplicity of a minimal API makes it easier to implement radical changes to the implementation of Quick Controls, and I love what's been accomplished in Qt's Quick Controls. Figuring out how to get what in this case is a bit of a puzzle, but as a beginner here I'm sure there are many interesting solutions I haven't thought of yet.