使用 QSyntaxHighlighter 隐藏文本
问题:我想为带有附加标签的文本实现一个文本编辑小部件。 我希望某些标签在某些情况下不可见,这样它们就不会分散用户的注意力。
环境:我正在使用PyQt
并且更喜欢使用QPlainTextWidget
和QSyntaxHighlighter
。
方法:使用QSyntaxHighlighter
,我可以为符合我的要求的字符串设置QTextCharFormat
。 QTextCharFormat
为我提供了所有字体属性,例如大小、颜色等。但是:我还没有找到隐藏文本或减少文本的选项其大小为零。
我不想删除或替换标签,因为这会引入更多代码(复制应该包含标签,如果没有标签,我就无法使用 QSyntaxHighlighter
根据标签格式化剩余文本) 。
更新:到目前为止,我发现了一个丑陋的黑客行为。通过将 QTextFormat::FontLetterSpacing 设置为较小的值,文本将占用越来越少的空间。与透明颜色相结合,文本就像是隐形的。
问题:在我的测试中,这只适用于字母间距低至 0.016% 的情况。下面的间距重置为 100%。
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 %.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此,您可以使用底层的
QTextDocument
。它由可以使用 setVisible 打开和关闭可见性的块组成。使用QTextCursor
插入文本和新块并切换可见性。作为奖励,复制功能无论如何都会复制不可见块的内容。注意:请参阅
QTextCursor
的文档了解更多信息信息。在 另一个问题中,报告设置可见性是不适用于QTextEdits
。例子:
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: