[Interest] QSyntaxHighlighter change QTextBlockFormat

Joshua Grauman jnfo-d at grauman.com
Wed Jan 5 05:30:29 CET 2022


Hi all,

I have been researching how to have a QSyntaxHighlighter change 
QTextBlockFormat. I need my syntax highlighter to change the indent, left 
and right margins, line height, etc. of a QTextDocument/QTextEdit.

I was able to have my class derived from QSyntaxHighlighter change the 
QTextBlockFormat of individual blocks easy enough using the QTextCursor 
interface, but the problem with that is that it messes up undo/redo 
functionality. All of the block format changes go onto the undo/redo stack 
and so make undo/redo unusable.

I have tried to find a way to modify QTextBlockFormat directly (getting 
the QTextLayout * of the current block and trying setPosition() on it, or 
even trying to move the individual lines of the QTextLayout), but it can't 
modify it here as I suspected (at least the way I tried it).

I can't find any other way to modify QTextBlockFormat in a way that won't 
be recorded onto the undo/redo stack.

So my options are (that I can see):

1) Roll my own complete undo/redo stack for QTextDocument/QTextEdit. This
    seems overkill since it's already written.

2) Modify Qt to be able to disable the undo/redo stack temporarily while
    the QSyntaxHighlighter is changing the block format. There's already a
    function QTextDocument::setUndoRedoEnabled(bool enable). But I can't
    use it directly because it clears the undo/redo stack (the docs says
    the undo stack, but the code looks like it's clearing the redo
    stack???). Either way I need to modify
    QTextDocument::setUndoRedoEnabled(bool enable) so that it can enable
    and disable undo/redo without clearing the stack(s). It would seem like
    I could add a second parameter to the function with a default value to
    work like it does currently, but with an option that can be added to
    not clear the stack. Although I've only written 2-3 patches for Qt,
    this seems easy enough that I could do it. But I wanted to check first
    if this seems like a reasonable approach and would be likely to be
    accepted.

Obviously, I would like to take option 2, but I wanted feedback first. 
Does that seem like a reasonable approach? Will it be likely to be 
included in Qt? I don't want to write a patch if there are clear problems 
with the approach. Also, if anyone has a way to easily modify the 
blockformat of a block without affecting undo/redo, that would be great. 
Or even if someone has rolled their own undo/redo for QTextDocument, I 
suppose I could use that. Thanks for any help, it is greatly appreciated.

Josh


More information about the Interest mailing list