Hiding text with QSyntaxHighlighter
Asked Answered
J

1

6

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 %.

Jerlenejermain answered 24/1, 2012 at 21:32 Comment(2)
Well, plain text is plain text. Try to use the non-plain widget.Docilla
I haven't found corresponding options in QTextEdit. AFAIK the difference is limited to the scrolling behavior, tables, frames and things like images. The functions which might enable to hide text are the same as for the QPlainTextEdit. Other then that there are mo more advanced classes inside Qt. QScintilla would mean using something completely different.Jerlenejermain
L
4

You can use the underlying QTextDocument for this. It consists of blocks whose visibility can be turned on and off using setVisible. Use a QTextCursor 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 on QTextEdits.

Example:

from PyQt5 import QtWidgets, QtGui

app = QtWidgets.QApplication([])

w = QtWidgets.QPlainTextEdit()
w.show()

t = QtGui.QTextCursor(w.document())
t.insertText('plain text')
t.insertBlock()
t.insertText('tags, tags, tags')
t.block().setVisible(False)

print(w.document().toPlainText())

app.exec_()
Lout answered 10/11, 2016 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.