You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQtGraph图例含<、>特殊字符时文本截断的原因及无替换方案咨询

PyQtGraph图例含特殊字符截断问题:原因与解决方案

问题原因

PyQtGraph的图例默认将名称按HTML格式解析,<和>属于HTML标签的边界符号,会被当作标签处理。比如TEST_O<C_C*0.99>=H中,<C_C*0.99>会被识别为无效HTML标签,后续的=H会被忽略,最终导致文本截断。

无需替换特殊字符的解决办法

方法1:手动设置图例项为纯文本渲染

添加图例后,遍历所有图例项,强制使用纯文本格式显示:

from PySide6 import QtCore, QtWidgets
import pyqtgraph as pg

plt = pg.plot()
legend = plt.addLegend()

c1 = plt.plot([1,2,3], pen='r', name="TEST_O<C_C*0.99>=H")
c2 = plt.plot([3,2,1], pen='g', name='green plot test blabla')

# 遍历图例项,切换为纯文本格式
for item in legend.items:
    item[1].setTextFormat(QtCore.Qt.TextFormat.PlainText)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtWidgets.QApplication.instance().exec()

方法2:自定义纯文本图例类

如果项目中需要多次使用纯文本图例,可以自定义一个继承自LegendItem的类,默认启用纯文本渲染:

from PySide6 import QtCore, QtWidgets
import pyqtgraph as pg
from pyqtgraph.graphicsItems.LegendItem import LegendItem

class PlainTextLegend(LegendItem):
    def addItem(self, item, name):
        super().addItem(item, name)
        # 对新添加的图例项设置纯文本格式
        last_label = self.items[-1][1]
        last_label.setTextFormat(QtCore.Qt.TextFormat.PlainText)

plt = pg.plot()
# 使用自定义图例
legend = PlainTextLegend(parent=plt.graphicsItem())
plt.addItem(legend)

c1 = plt.plot([1,2,3], pen='r', name="TEST_O<C_C*0.99>=H")
c2 = plt.plot([3,2,1], pen='g', name='green plot test blabla')

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtWidgets.QApplication.instance().exec()

内容的提问来源于stack exchange,提问作者jamesB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:07:27