您必须使用样式和 QFontDatabase 才能使用Roboto-MediumItalic
. 您还可以通过 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()