4

Is it possible to use google fonts in a PyQt5 application? I'm trying to add some text to a pixmap and want to be able to use google fonts if possible. https://fonts.google.com/.

I haven't been able to find anything online regarding this.

def addText(pixmap, w, h, name):
    painter = QPainter()        
    font = painter.font()
    font.setPointSize(36);
    painter.begin(pixmap)
    position  = QtCore.QRect(0, 0, w,h)
    painter.setFont(font);
    painter.drawText(position, Qt.AlignCenter, name);
    painter.end()
    return pixmap

Any ideas on how to make this work if it is possible? Thanks in adcance

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

9

You have to download the font and add it with QFontDatabase::addApplicationFont(), by example:

from PyQt5 import QtCore, QtGui, QtWidgets

def addText(pixmap, w, h, name):
    painter = QtGui.QPainter(pixmap)        
    font = QtGui.QFont("Roboto")
    font.setPointSize(36)
    position  = QtCore.QRect(0, 0, w, h)
    painter.setFont(font);
    painter.drawText(position, QtCore.Qt.AlignCenter, name);
    painter.end()
    return pixmap

def create_pixmap():
    pixmap = QtGui.QPixmap(512*QtCore.QSize(1, 1))
    pixmap.fill(QtCore.Qt.white)
    return addText(pixmap, 512, 512, "Stack Overflow")

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    dir_ = QtCore.QDir("Roboto")
    _id = QtGui.QFontDatabase.addApplicationFont("Roboto/Roboto-Regular.ttf")
    print(QtGui.QFontDatabase.applicationFontFamilies(_id))
    w = QtWidgets.QLabel()
    w.setPixmap(create_pixmap())
    w.show()
    sys.exit(app.exec_())

enter image description here

The example can be found here.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241