如何在 QLabel 中设置文本并显示 '<>' 字符?

How to set text in a QLabel and display '<>' characters?

使用 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 &lt%d&gt 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 的建议在字符串中使用了 &lt&gt,但在生成的 QLabel 文本中没有得到“<”或“>”

我要打印 status: Influence count <7> exceeds minimum row count...

但它实际上打印 status: Influence count &lt7&gt exceeds minimum row count...

在两者中,'status:' 是白色的,而其余的是预期的红色。

注意:在字符串中使用 '<%d>' 会导致 status: Influence count exceeds minimum row count...

我还需要做什么才能正确格式化字符串?

QLabelclass自动支持rich-text, so you need to use character entity references to escape special characters. For <, use &lt; and for >, use &gt;. If you can't edit the text directly, use html.escape进行转换。

或者,要完全关闭富文本支持,您可以这样做:

label.setTextFormat(QtCore.Qt.PlainText)