PyQt6 – Adding Custom Fonts

PyQt6 offers various default fonts that we can use to change the style of our text. But often these fonts are not enough, and we need to import some Custom Fonts into our PyQt6 Application. In this PyQt6 tutorial, we will explore how to do so.


Adding Custom Fonts

The first thing we need to do, is add the Custom Font to the QFontDatabase.

from PyQt6.QtGui import QFont, QFontDatabase

First import the QFont and QFontDatabase Classes from PyQt6.QtGUI.

id = QFontDatabase.addApplicationFont("Frostbite.ttf")
if id < 0: print("Error")

Next, add the font file you downloaded to our QFontDatabase using the addApplicationFont() function. Simply pass in the file path, or file name of the Font File into this function, and it will be ready for use.

If you want the fonts we are using in this tutorial, use this download link.

We need to find out the name of the Font File we just added. This information is stored within the Font file, and can be acquired by calling the following function.

families = QFontDatabase.applicationFontFamilies(id)

The reason why we need it’s name, is because we require it as an argument when changing our Fonts from default to custom.

Here we create a simple QLabel Widget to display some text. We then change the Font of this label widget, by passing in a QFont Object.

label = QLabel("Hello World", self)
label.setFont(QFont(families[0], 80))

QFont objects take two main parameters. The first is the name of the Font, and the second is the Font size.

If all went well, our QLabel will now have the text “Hello World”, using the Font “Frostbite” with a size of 80.


Complete Code

Here is the complete code required to add a Custom Font in PyQt6. Just remember to download and place the Font File in the appropriate location.

from PyQt6.QtWidgets import QApplication, QWidget, QLabel
from PyQt6.QtGui import QFont, QFontDatabase
import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(600, 300)
        self.setWindowTitle("CodersLegacy")
        self.setContentsMargins(20, 20, 20, 20)

        id = QFontDatabase.addApplicationFont("Frostbite.ttf")
        if id < 0: print("Error")

        families = QFontDatabase.applicationFontFamilies(id)
        print(families[0])

        label = QLabel("Hello World", self)
        label.setFont(QFont(families[0], 80))
        label.move(50, 100)

app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())

Want to learn more about PyQt6 and it’s various applications? Follow the link for more!


This marks the end of the PyQt6, Adding Custom Fonts Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarded the tutorial can be asked in the comments section.

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments