3

是否可以在 PyQt5 应用程序中使用谷歌字体?我正在尝试向像素图中添加一些文本,并希望能够在可能的情况下使用谷歌字体。https://fonts.google.com/

我无法在网上找到任何关于此的内容。

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

如果可能的话,关于如何完成这项工作的任何想法?提前致谢

4

1 回答 1

8

您必须下载字体并添加它QFontDatabase::addApplicationFont(),例如:

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_())

在此处输入图像描述

该示例可在此处找到。

于 2018-12-19T18:48:36.083 回答