使用 PySide2(基本上是 PyQt5),我正在尝试 setText
在字符串中包含字符“<”和“>”的 QLabel 中。但是,由于这些字符用于修改字体,因此这两个字符中的任何内容都会消失。我尝试用反斜杠转义它们,但似乎仍然不起作用......
如何让“<”和“>”字符显示在 QLabel 中?
编辑:这是我的代码正在做的一些事情(只是捕获了重要的部分):
# color and text get set at various places in my code (len_infs is just the length of the
# influence item list - hopefully that's obvious...)
#
color = '#FF0000'
text = 'Influence count <%d> exceeds minimum row count...' %len_infs
# status_label is a QLabel that displays the text in the appropriate color within the label
#
status_label.setText('status: <font color=%s>%s</font>' %(color, text))
如您所见,我正在使用 <
和>
在基于 ekhumoro 的建议的字符串中,但我在生成的 QLabel 文本中没有得到“<”或“>”
我希望它打印status: Influence count <7> exceeds minimum row count...
但它实际上打印 status: Influence count <7> exceeds minimum row count...
在这两种情况下,“状态:”均为白色,而其余部分则按预期为红色。
注意:使用'<%d>'
字符串结果为 status: Influence count exceeds minimum row count...
我还需要做什么才能正确格式化字符串?
最佳答案
QLabel
类自动支持rich-text ,所以你需要使用character entity references转义特殊字符。对于 <
,使用<
和 >
,使用>
。如果您无法直接编辑文本,请使用 html.escape进行转换。
或者,要完全关闭富文本支持,您可以执行以下操作:
label.setTextFormat(QtCore.Qt.PlainText)
关于python - 如何在 QLabel 中设置文本并显示 '<>' 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47584343/