Search code examples
pythonpyside2

Process finished with exit code 1 while getting Font


I have some simple code that grabs the font from my resources directory and assigns it to a QFont

I can't get anything to print, none of the variables. It just keeps returning exit code 1.

Sorry I don't really know what exactly to try here. So I have nothing show of what I tried. I did make sure to test that the FONT_PATH is going to a correct file. Also this function seems to work fine when called from a 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()

What I'm expecting:

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

What I'm getting:

Process finished with exit code 1


Solution

  • If you run your script in the CMD/terminal you will get the following error message:

    QFontDatabase: Must construct a QGuiApplication before accessing QFontDatabase
    

    And that message indicates that you must have a QGuiApplication (or QApplication) before using QFontDatabase, so in your case you must create it if it does not exist:

    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())