如何使用非标准自定义字体与样式表?

14

我有一个使用PyQt4编写的应用程序,通过使用以下代码,可以使用外部的.qss文件来设置其样式:

...
app = QtGui.QApplication(sys.argv)
stylesheet = open('mystylesheet.qss').read()
app.setStyleSheet(stylesheet)
...

通常我会在.qss文件中指定我喜欢的字体类型,像这样使用:

QMainWindow
{
font-family:arial;
font-size:14px;
}

现在我想知道是否可以将我从互联网上下载的自定义字体(例如DroidSansMono(True Type字体))赋给文本,而不是使用Windows标准字体?

注:我使用的是Windows XP SP3 32位操作系统和Python 2.7

更新1:

根据Ekhumoro的回答:

我可以通过将其添加到字体数据库中以在加载Stylesheet之前使用下载的自定义字体。

QtGui.QFontDatabase.addApplicationFont("Resources/Mf Wedding Bells.ttf")

之后,我可以在样式表中使用刚刚添加的字体名称,就像这样:

After that, I can simply use the font name that I have just added in the stylesheet like this:

QLabel
{
font-family:Mf Wedding Bells;
font-size:16px;
}

它有效了!!!

1个回答

15

我只是猜测,因为我无法自己测试,但您可以在设置样式表之前尝试加载字体

app = QtGui.QApplication(sys.argv)
QtGui.QFontDatabase.addApplicationFont('path/to/font')
# or load the font data directly
# QtGui.QFontDatabase.addApplicationFontFromData(fontdata)
stylesheet = open('mystylesheet.qss').read()
app.setStyleSheet(stylesheet)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接