简体   繁体   English

PyQt5:使用谷歌字体

[英]PyQt5: Using google fonts

Is it possible to use google fonts in a PyQt5 application? 是否可以在PyQt5应用程序中使用谷歌字体? I'm trying to add some text to a pixmap and want to be able to use google fonts if possible. 我正在尝试向pixmap添加一些文本,并希望能够使用谷歌字体。 https://fonts.google.com/ . 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 谢谢你的加入

You have to download the font and add it with QFontDatabase::addApplicationFont() , by example: 您必须下载字体并使用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_())

在此输入图像描述

The example can be found here . 这个例子可以在这里找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM