Search code examples
qtqmlqfontqfontmetrics

Why is there a mismatch in width provided by QFontMetrics and width shown by Qml Rectangle/ Text


I have written a qml and cpp file to validate and visualize QFontMetrics concept.

#include <QFontMetrics>
#include<QFontMetricsF>
#include<QDebug>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

QString translation = " Sort médicament à la liste des filtres";
QString fontname = "Frobisher";
int size = 28;

QFont font(fontname,size);
QFontMetrics fm(font);
int pixelsWide = fm.width(translation);


qDebug()<<"width "<<pixelsWide;
return app.exec();
}

main.qml file

Window 
{
visible: true
width: 940
height: 480
title: qsTr("Hello World")

Rectangle
{
    color: "blue"
    width: 642
    height: 47
    Text {
        id: txt
        anchors.fill: parent
        anchors.centerIn: parent.Center
        text: qsTr(" Sort médicament à la liste des filtres")
        font.family: "Frobisher"
        font.bold: true
        font.pixelSize: 28
        elide: Text.ElideRight

    }
}
}

When I run this program, width provide by QFontMetrics is : 694. But, width set in qml file for Rectangle and Text is 642 and elide property is set too. With this logic (as 694 > 642) I should be seeing truncation. But no truncation is seen.

please refer qml output

Why is this? Not able to understand.


Solution

  • The fonts are different since on the C++ side you have established that the pointSize is 28 but on the QML side you have established that the pixelSize is 28 (to know the difference between point size and pixel size check this post)


    TL; DR;

    On the C++ side you have used this constructor:

    QFont::QFont(const QString &family, int pointSize = -1, int weight = -1, bool italic = false)

    Where you clearly set the pointSize to 28, but in QML you set as pixelSize at 28:

    Text {
        // ...
        font.bold: true
        font.pixelSize: 28
        // ...

    The solution is to use the same characteristics of the font:

    Text {
        // ...
        font.bold: true
        font.pointSize: 28
        // ...

    enter image description here


    Note: From Qt>=5.11 you should use horizontalAdvance() instead of width() since the latter is deprecated.