Important: Please read the Qt Code of Conduct -

text width using font family and font size

  • hello ,

    i am trying to find the maximum width required to fit a text with specific font family and font size.

    qt is not returning exact width for text, and it seems not considering font family also.

    here is my code in cpp

    int UIUtilities::findTextWidth(const QString &text, const QString &fontName, int fontSize, int maxWidth) const
    QFont myFont(fontName, fontSize);;
    QString str(text);
    QFontMetrics fm(myFont);
    int width=fm.width(str);
    if(width < maxWidth) return width;
    else return maxWidth;

    here is the calling line in qml.

    width: UIUtil.findTextWidth("hello", "Garamond", 16,100 )
    width: UIUtil.findTextWidth("hello", "SomeRandomName....", 16,100 )

    above both values are same!!
    does qt really identifies which family we are referring to recognize width of a character?, as width of character varies with different font families even with same pixel size.


  • Moderators

    Qt will automatically fall back to known fonts when you try to use a non-existing font. So it is very probable that you get the same value because Qt fell back to the same font behind the scenes.

    Try to first validate that the font you requested really exists and was loaded.

  • how can i validate the font.

  • Moderators

    This QFont::exactMatch() or you can check against installed families in QFontDatabase.

Log in to reply