Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding text with QSyntaxHighlighter

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

like image 422
m2j Avatar asked Jan 24 '12 21:01

m2j


1 Answers

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_()
like image 162
Trilarion Avatar answered Oct 06 '22 23:10

Trilarion