进程在获取字体时以退出代码 1 完成

Process finished with exit code 1 while getting Font

我有一些简单的代码可以从我的资源目录中获取字体并将其分配给 QFont

我无法打印任何变量,none。它只是不断返回退出代码 1。

抱歉,我真的不知道该尝试什么。所以我没有展示我尝试过的东西。我确实确保测试 FONT_PATH 是否指向正确的文件。此外,从 QApplication

调用时,此函数似乎也能正常工作
from PySide2 import QtGui, QtCore
import os

def get_font():

    FONT_PATH = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, 'resources', 'ProximaNova-Regular.ttf'))
    FONT_DB = QtGui.QFontDatabase()
    FONT_ID = FONT_DB.addApplicationFont(FONT_PATH)
    FAMILIES = FONT_DB.applicationFontFamilies(FONT_ID)
    BOLD_FONT = QtGui.QFont('Proxima Nova')

    return BOLD_FONT

print get_font()

我期待的是:

<PySide2.QtGui.QFont( "Proxima Nova....") at 0x000....>

我得到的:

Process finished with exit code 1

如果您 运行 您的脚本在 CMD/terminal 中,您将收到以下错误消息:

QFontDatabase: Must construct a QGuiApplication before accessing QFontDatabase

并且该消息表明在使用 QFontDatabase 之前您必须有一个 QGuiApplication(或 QApplication),因此如果它不存在,您必须创建它:

import os

from PySide2 import QtGui, QtCore


def get_font():
    app = QtGui.QGuiApplication.instance()
    if app is None:
        app = QtGui.QGuiApplication([])
    FONT_PATH = os.path.abspath(
        os.path.join(
            __file__, os.pardir, os.pardir, "resources", "ProximaNova-Regular.ttf"
        )
    )
    FONT_DB = QtGui.QFontDatabase()
    FONT_ID = FONT_DB.addApplicationFont(FONT_PATH)
    FAMILIES = FONT_DB.applicationFontFamilies(FONT_ID)
    BOLD_FONT = QtGui.QFont("Proxima Nova")
    return BOLD_FONT


print(get_font())