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

标签 python html pyqt5 qlabel pyside2

使用 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))

如您所见,我正在使用 &lt&gt在基于 ekhumoro 的建议的字符串中,但我在生成的 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...

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

最佳答案

QLabel类自动支持rich-text ,所以你需要使用character entity references转义特殊字符。对于 < ,使用&lt;> ,使用&gt; 。如果您无法直接编辑文本,请使用 html.escape进行转换。

或者,要完全关闭富文本支持,您可以执行以下操作:

label.setTextFormat(QtCore.Qt.PlainText)

关于python - 如何在 QLabel 中设置文本并显示 '<>' 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47584343/

相关文章:

python - 在 Python pandas 中,从 1 而不是 0 开始行索引而不创建额外的列

python - Seaborn自动选色

python - python初始条件中的快速排序算法

python - 将 QPixmap 保存到 PostgreSQL 而不使用准备好的查询

qt - 使用 PyQt5 在 Python3 中的当前屏幕大小

python - 如何使用 Python 将我的 GoPro Hero 4 摄像机实时流连接到 openCV?

php - 如何创建 RSS 提要并显示它?

javascript - 如何选择与 jQuery 具有部分字符串匹配的所有元素

javascript - .nextAll 不适用于动态内容

python - 为另一个类中的小部件设置背景图像