如何在QLabel中设置文本并显示'<>'字符? [英] How to set text in a QLabel and display '<>' characters?

查看:73
本文介绍了如何在QLabel中设置文本并显示'<>'字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PySide2(基本上是PyQt5),我尝试在字符串中包含字符‘<;’和‘>’的QLabel中setText。但是,由于这些字符用于修改字体,这两个字符内的任何内容都会消失。我试着用反斜杠转义,但似乎还是不行…

如何使‘<;’和‘>’字符显示在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:"都是白色的,而睡觉的"Status:"是预期的红色。

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

我还需要执行哪些操作才能正确设置字符串的格式?

推荐答案

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

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

label.setTextFormat(QtCore.Qt.PlainText)

这篇关于如何在QLabel中设置文本并显示&#39;&lt;&gt;&#39;字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆