QTextDocument.setHtml() + CSS @font-face

  • Hi,
    I'm using a QTextDocument and the setHtml() function the generate some documents.
    On the document i'd like to have a specific text in a custom font.

    QString css = "..."; //some css
    css += "@font-face { font-family: MyFont; src: url('MyFont.ttf'); }";
    QString html = ".." //some html
    html += "<span style=\"font-family:myFont;\">text</span>";

    but sadly the text in the document doesn't change to my font.
    The file "MyFont.tff" is in the same directory as the binary;
    Also: installing the font in C:\Windows\Fonts is not an option;
    How can I asign MyFont to the text?

    thx for helping ;)

  • Lifetime Qt Champion

    hi and welcome
    Try with

    QString FullPathFont( qApp->applicationDirPath()+"/"+" "MyFont.tff");
    qDebug() << "font:" << FullPathFont; // please check its correct :)
    int id = QFontDatabase::addApplicationFont(FullPathFont);

    check id. -1 means not loaded.

    This should make the font available to your app .

  • Thank you,
    Problem solved.
    For future reference:

    int fontID = QFontDatabase::addApplicationFont("MyFont.ttf");
    QString fontFamily = QFontDatabase::applicationFontFamilies(fontID).at(0);
    html += "<span style=\""+fontFamily+"\">text</span>";

Log in to reply