Hiding text with QSyntaxHighlighter

此生再无相见时 提交于 2019-12-14 00:58:10

问题


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


回答1:


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_()


来源:https://stackoverflow.com/questions/8994502/hiding-text-with-qsyntaxhighlighter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!