PyQt6中如何通过相对路径加载自定义.ttf字体?
如何用相对路径在PyQt6中加载自定义TTF字体
核心问题:相对路径的基准目录错误
你遇到的问题本质是Python的相对路径基于当前工作目录(CWD),而非脚本所在目录。如果运行脚本时的工作目录和脚本所在目录不一致,直接用"rsrc/xxx.ttf"这种相对路径会找不到文件。
解决方案:基于脚本目录构建绝对路径
通过获取脚本文件的绝对路径,再拼接字体的相对路径,就能确保无论从哪个目录运行脚本,都能正确找到字体文件。下面提供两种实现方式:
方式1:使用pathlib(推荐,Python 3.4+)
修改你的测试脚本如下:
from PyQt6.QtWidgets import QApplication, QWidget, QLabel from PyQt6.QtGui import QFont, QFontDatabase import sys from pathlib import Path class Window(QWidget): def __init__(self): super().__init__() self.resize(600, 300) self.setWindowTitle("CodersLegacy") self.setContentsMargins(20, 20, 20, 20) # 获取脚本所在目录 script_dir = Path(__file__).parent # 拼接字体的相对路径 font_path = script_dir / "rsrc" / "ITCAvantGardeStd.ttf" # 加载字体(需要转成字符串,因为addApplicationFont接受字符串路径) font_id = QFontDatabase.addApplicationFont(str(font_path)) if font_id < 0: print(f"加载字体失败,路径:{font_path}") else: print(f"Success {font_id}") families = QFontDatabase.applicationFontFamilies(font_id) if families: print(families[0]) label = QLabel("Hello World", self) label.setFont(QFont(families[0], 80)) label.move(50, 100) else: print("未找到该字体对应的字体族") app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec())
方式2:使用os.path(兼容旧版Python)
如果你的Python版本较低,改用os模块处理路径:
from PyQt6.QtWidgets import QApplication, QWidget, QLabel from PyQt6.QtGui import QFont, QFontDatabase import sys import os class Window(QWidget): def __init__(self): super().__init__() self.resize(600, 300) self.setWindowTitle("CodersLegacy") self.setContentsMargins(20, 20, 20, 20) # 获取脚本所在目录的绝对路径 script_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接字体路径 font_path = os.path.join(script_dir, "rsrc", "ITCAvantGardeStd.ttf") font_id = QFontDatabase.addApplicationFont(font_path) if font_id < 0: print(f"加载字体失败,路径:{font_path}") else: print(f"Success {font_id}") families = QFontDatabase.applicationFontFamilies(font_id) if families: print(families[0]) label = QLabel("Hello World", self) label.setFont(QFont(families[0], 80)) label.move(50, 100) else: print("未找到该字体对应的字体族") app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec())
针对你的main.py修改
同样用上述方法构建字体路径,确保加载成功:
from PyQt6.QtWidgets import QApplication from PyQt6.QtGui import QFontDatabase import sys from pathlib import Path app = QApplication(sys.argv) # 构建字体路径 script_dir = Path(__file__).parent font_path = script_dir / "rsrc" / "ITCAvantGardeBk.ttf" font_id = QFontDatabase.addApplicationFont(str(font_path)) # 加载样式表 style_path = script_dir / "styles.qss" with open(style_path, 'r') as stlf: style = stlf.read() app.setStyleSheet(style) sys.exit(app.exec())
QSS的注意事项
既然你已经通过QFontDatabase.addApplicationFont将字体加载到了应用的字体库中,不需要在QSS中使用@font-face,直接使用字体族名即可(注意和applicationFontFamilies返回的名称一致,比如你的测试中返回的是ITC Avant Garde Gothic Std,而不是ITCAvantGardeBk,这可能也是你之前报错的原因之一——字体族名和文件名不一致)。
修改后的styles.qss:
QLabel { font-family: 'ITC Avant Garde Gothic Std'; }
调试技巧
如果还是加载失败,先打印路径确认是否正确:
print("当前工作目录:", os.getcwd()) print("字体绝对路径:", font_path)
检查输出的字体路径是否和实际文件位置一致。
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

