2

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

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

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

在这两种情况下,“状态:”都是白色的,而其余的则是预期的红色。

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

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

4

1 回答 1

3

该类QLabel自动支持富文本,因此您需要使用字符实体引用来转义特殊字符。为<,使用&lt;和为>,使用&gt;。如果无法直接编辑文本,请使用html.escape进行转换。

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

label.setTextFormat(QtCore.Qt.PlainText)
于 2017-12-01T00:36:21.947 回答