How do I addApplicationFont() in MacOS? Font is in Python script folder...



  • I've done quite a bit of googling and found some interesting info but haven't been able to solve this. If I have a ttf font in the same folder as my Python script and I do something like this:

    fontbase = QtGui.QFontDatabase()
    test = fontbase.addApplicationFont("MySillyFont")
    font = QtGui.QFont("MySillyFont")
    app.setFont(font)
    

    I find that a) test is = to -1 (meaning it didn't load the font)
    b) Qt just uses Lucida Grande c) A Qt font dialog box doesn't (obviously) find the MySillyFont.
    If I run the same code on Linux, it works; MySillyFont loads and is available in a Qt Font Dialog Box.

    Now, I've read about needing fontconfig in order to load fonts in Unix/X11 so I tried installing that with brew. I still get the same behavior. I'm wondering if I'm just having a problem with the path to the font but any of my experiments have not revealed the issue. I'd like to be able to just distribute the font with the scripts folder rather than installing the font through the OS on the target systems...


  • Lifetime Qt Champion

    Hi
    I think its just a path problem.
    I dont know how mac handles current folder but
    Can you try outout
    QDir::currentPath())
    and see if we are in the script folder.
    Might not even work that way with python but its worth a check :)

    Using c++ people often use a resource file to hold the font.
    However, python having no real.exe I'm not sure how that works.



  • As @mrjj mentioned this is just a path problem. So if your font file is in the same folder you can do this:

    QFontDatabase.addApplicationFont(os.path.dirname(__file__) + "/filename")
    

    If you have a "scripts" folder that resides in the same location as you main file:

    QFontDatabase.addApplicationFont(os.path.dirname(__file__) + "/scripts/filename")
    


  • @daljit97

    Aha, the path is the issue.
    So, I find that using daljit97's approach does allow the font to be loaded in MacOS. But it fails on Linux. :( This means I need to parse this according to platform.

    fontbase = QtGui.QFontDatabase()
    test = fontbase.addApplicationFont(os.path.dirname(__file__) + "/MySillyFont.ttf")
    font = QtGui.QFont("MySillyFont", 12)
    app.setFont(font)
    

    And, on MacOS I'm able to load the font at start but the font dialog box does not show it. I'm still missing something simple here. It's not clear to me... How should my fontDialog know about the database I created? For that matter, how does the app know about the database at the very beginning? It somehow finds the font in the above code but doesn't find the font in my Fonty function.

    def Fonty():
        ok, font = QtWidgets.QFontDialog.getFont()
        print(f"font selected is {font}")
        if ok:
            app.setFont(font)
    

 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.