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

如何通过PyQt6的QFontComboBox为Matplotlib正确设置QtGui.QFont字体

解决Matplotlib无法识别QFontComboBox所选字体的问题

1. 确认Matplotlib实际识别的字体族名

QFontComboBox返回的字体名称可能和Matplotlib内部登记的名称存在差异(比如你遇到的"Microsoft YaHei UI",Matplotlib可能仅识别"Microsoft YaHei")。运行以下代码查看Matplotlib已加载的所有字体信息:

import matplotlib.font_manager as fm
for font in fm.fontManager.ttflist:
    print(f"{font.name} | {font.fname}")

找到你添加的字体对应的font.name值,这个才是Matplotlib能正确识别的字体族名。

2. 刷新Matplotlib字体缓存

即使将字体放入font/ttf目录,Matplotlib也可能未更新缓存。手动删除缓存文件即可触发重新扫描:

  • Windows:缓存路径通常为C:\Users\<你的用户名>\.matplotlib\fontlist-v330.json(版本号可能随Matplotlib版本变化)
  • Linux/macOS:缓存路径通常为~/.cache/matplotlib/fontlist-v330.json
    删除文件后重启Python,Matplotlib会重新生成字体缓存。

3. 适配QFontComboBox的字体名映射

如果QFontComboBox返回的名称和Matplotlib识别的名称不一致,可通过映射表转换:

# 根据实际查到的字体名称调整映射关系
font_name_mapping = {
    "Microsoft YaHei UI": "Microsoft YaHei",
    # 可添加其他需要转换的字体对
}

# 获取QFontComboBox选中的字体名
selected_font = font_combo.currentFont().family()
# 转换为Matplotlib可识别的名称
mpl_font = font_name_mapping.get(selected_font, selected_font)

# 全局设置Matplotlib字体
plt.rcParams['font.sans-serif'] = [mpl_font]
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示异常问题

# 绘制图表时即可生效
plt.title("测试标题", fontsize=14)
plt.xlabel("X轴标签")
plt.ylabel("Y轴标签")

4. 直接指定字体文件路径(备选方案)

若上述方法仍无效,可跳过字体族名识别,直接通过字体文件路径设置:

from matplotlib.font_manager import FontProperties

# 替换为你实际的字体文件路径
font_path = r"C:\Python\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\msyh.ttc"
custom_font = FontProperties(fname=font_path)

# 为标题和标签单独设置字体
plt.title("测试标题", fontproperties=custom_font)
plt.xlabel("X轴标签", fontproperties=custom_font)
plt.ylabel("Y轴标签", fontproperties=custom_font)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:05:59