Search code examples
c++qtstylesheetqtstylesheets

How to use a embedded font in Qt Style Sheet?


I added a font name ":font/Oswald-Regular.ttf" in my .qrc resource file. I would like to use it in my Qt Style Sheet for all QLabels.

This is the code for Arial :

QLabel
{
color: white;
font: 10pt "Arial";
}

Solution

  • Add the font to the font database in your main:

    QFontDatabase::addApplicationFont(":/fonts/Oswald-Regular.ttf");
    

    You may want to check the function return value (0 indicates success) and/or the fonts available in the database:

      QFontDatabase db;
      for(int i=0; i<db.families().size(); i++)
      {
        qDebug() << db.families().at(i);
      }
    

    and see if "Oswald" appears in the list.

    Set the stylesheet to the label parent widget, from editor change stylesheet dialog:

    QLabel { color: black; font: 24pt  'Oswald'; }
    

    or programmatically in the widget constructor:

    setStyleSheet("QLabel { color: black; font: 24pt  'Oswald'; }");
    

    If on Unix/X11 platforms, be sure fontconfig is installed.