How to use Non-Standard Custom Font with Stylesheets?

Chris Aung picture Chris Aung · Jan 15, 2015 · Viewed 8.1k times · Source

I have a PyQt4 application that is being styled by an external .qss file by using the following code:

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

Normally, I would specify the type of font that I like in the .qss file to use like this:

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

But, now I am wondering if it is possible for me to assign a custom font that I downloaded from internet (example, DroidSansMono (True Type Font) ) instead of windows standard font?

NOTE: I am using Windows XP SP3 32 bits, with Python 2.7

UPDATE 1:

Based on Ekhumoro answer:

I can use the custom font downloaded by adding it to the font database before loading the 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;
}

And it works!!!

Answer

ekhumoro picture ekhumoro · Jan 15, 2015

This is just a guess, because I cannot test it myself, but you could try loading the font before setting the stylesheet:

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)