Problem: I want to implement a text editing widget for text with additional tags. I'd like some tags to be invisible in some cases so that they do not distract the user.
Environment: I'm using PyQt
and prefer to use QPlainTextWidget
and QSyntaxHighlighter
.
Approach: With QSyntaxHighlighter
I can set QTextCharFormat
for the strings which match my requirement. QTextCharFormat
has gives me all font properties like size, colors, etc. but: I haven't found a option to hide the text or reduce its size to zero.
I don't want to remove or replace the tags, as this will introduce a lot more code (copying should contain tags and without I can't use QSyntaxHighlighter
for formating the remaining text according to the tags).
Update: So far I found a ugly hack. By setting the QTextFormat::FontLetterSpacing to a small value, the text will consume less and less space. In combination with a transparent color the text is something like invisible.
Problem: In my test this worked only for letter spacings down to 0.016 %. Below the spacing is reseted to 100 %.
You can use the underlying
QTextDocument
for this. It consists of blocks whose visibility can be turned on and off usingsetVisible
. Use aQTextCursor
to insert the text and new blocks and switch visibility. As a bonus the copy function copies the content of non-visible blocks anyway.Notes: See the documentation of
QTextCursor
for more information. In another question here is was reported that setting the visibility is not working onQTextEdits
.Example: