How to select another type of font with QFont?

5.7k Views Asked by At

I am trying to assign different types of text fonts to my application with PyQt5, but I don't know how to assign a different one to the standard one, for example in my application I could only assign it 'Roboto', but if I want to change to Roboto-MediumItalic, I don't know how to specify that font type to it, i'm newbie to python and pyqt5

QFontDatabase.addApplicationFont("Static/fonts/Roboto-Light.ttf")
label2.setFont(QFont('Roboto',12))

folders

1

There are 1 best solutions below

0
On BEST ANSWER

You have to use the styles and QFontDatabase to use Roboto-MediumItalic. You can also set the italic weight style through QFont.

import os
import sys
from pathlib import Path

from PyQt5.QtCore import Qt, QDir
from PyQt5.QtGui import QFont, QFontDatabase
from PyQt5.QtWidgets import QApplication, QLabel

CURRENT_DIRECTORY = Path(__file__).resolve().parent


def load_fonts_from_dir(directory):
    families = set()
    for fi in QDir(directory).entryInfoList(["*.ttf"]):
        _id = QFontDatabase.addApplicationFont(fi.absoluteFilePath())
        families |= set(QFontDatabase.applicationFontFamilies(_id))
    return families


def main():

    app = QApplication(sys.argv)

    font_dir = CURRENT_DIRECTORY / "Static" / "fonts"
    families = load_fonts_from_dir(os.fspath(font_dir))
    print(families)

    db = QFontDatabase()
    styles = db.styles("Roboto")
    print(styles)

    font = db.font("Roboto", "Medium Italic", 12)

    # OR
    # font = QFont("Roboto", pointSize=12, weight=QFont.Medium, italic=True)

    label = QLabel(alignment=Qt.AlignCenter)
    label.setFont(font)
    label.setText("Hello world!!")
    label.resize(640, 480)
    label.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()