为什么我的自定义字体实现在 pyqt5 中不起作用?

why does my custom font implementation not work in pyqt5?

我正在尝试在 pyqt5 中使用自定义字体,经过一番搜索后很明显我必须使用 QFontDatabase.addApplicationFont()。所以我实现了它并且文件似乎具有正确的路径(我重命名了文件并且我的 python 中的名称也更改了)。但是,当我使用此代码时,我得到了标准字体:

Fontdb = QFontDatabase
Fontdb.addApplicationFont("Omega.ttf")

class Centre(QWidget):
  def __init__(self):
    super().__init__()
    x1 = int(Centralwidth * 0.08333)
    y1 = int(Centralheight * 0.083333)
    self.setGeometry(int(x1-10), int(y1-10), int(Centralwidth-10), int(Centralheight-10))

  def paintEvent(self, event):
    painter = QPainter(self)
    painter.setPen((QPen(QColor(50, 225, 255, 215), 13, Qt.DashLine)))

    x1 = int(Centralwidth * 0.08333)
    y1 = int(Centralheight * 0.083333)
    dottedcircle = QRectF(x1, y1, 640, 640)
    Arc1 = dottedcircle.adjusted(20, 20, -20, -20)
    Arc2 = dottedcircle.adjusted(25, 25, -25, -25)
    Arc3 = dottedcircle.adjusted(45, 45, -45, -45)
    Arc4 = dottedcircle.adjusted(40, 40, -40, -40)
    Arc5 = dottedcircle.adjusted(50, 50, -50, -50)
    painter.drawEllipse(dottedcircle)

    painter.setPen((QPen(QColor(50, 175, 255, 200), 40)))
    painter.drawArc(Arc1, 1440, 3200)
    painter.setPen((QPen(QColor(50, 150, 230, 190), 30)))
    painter.drawArc(Arc2, 5120, 1440)
    painter.setPen((QPen(QColor(50, 175, 230, 150), 25)))
    painter.drawArc(Arc3, 2240, 1600)
    painter.setPen((QPen(QColor(50, 180, 255, 140), 20)))
    painter.drawArc(Arc4, 4480, 1520)
    painter.setPen((QPen(QColor(50, 160, 255, 210), 50)))
    painter.drawArc(Arc5, 800, 900)
    painter.drawArc(Arc5, 3680, 900)

    painter.setFont(QFont("Omega", 60))
    painter.drawText(dottedcircle, Qt.AlignCenter, "A.G.O.S.")



app = QApplication(sys.argv)
window = Centre()
window.show()

sys.exit(app.exec_())

首先,您需要确保字体正确加载,并且可以通过显示addApplicationFont().[=17的结果轻松检查。 =]

fontId = QFontDatabase.addApplicationFont("Omega.ttf")
if fontId < 0:
    print('font not loaded')

然后,QFont 构造函数的参数不是文件名,而是字体系列。您可以使用 applicationFontFamilies 之前返回的字体 ID 使用 addApplicationFont():

返回的字体 ID 来检查它们
families = QtGui.QFontDatabase.applicationFontFamilies(fontId)
font = QtGui.QFont(families[0])

最后,addApplicationFont 应该总是 QApplication 实例创建之后被调用。