qtfontsqmlqt5stretch

Font stretching in QML


We are converting some older QT widget code to use QML and I cannot find the equivalent property for the QFont::setStretch() operation.

The QML Font page shows only family, bold, italic, underline, pointSize, pixelSize, weight, overline, strikeout, capitalization, letterSpacing, wordSpacing, kerning, preferShaping and hintingPreference.

This font selection is being done within a Text object, along the lines of:

Text {
    font.family: "LiberationSans"
    font.pixelSize: 178
    font.weight: 80
    //font.stretch: 75 - doesn't work, no such property
}

Is there no way to set the stretch factor in QML. We're using Qt 5.6 by the way.


Solution

  • Unfortunately this property is not exposed to QML, a possible solution is to use a helper class that receives the QFont, change the stretch and return the new QFont.

    main.cpp

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlContext>
    #include <QFont>
    
    class FontHelper: public QObject{
        Q_OBJECT
    public:
        using QObject::QObject;
        Q_INVOKABLE QFont changeStretchFont(const QFont & font, int factor){
            QFont fn(font);
            fn.setStretch(factor);
            return fn;
        }
    };
    
    int main(int argc, char *argv[])
    {
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
        FontHelper helper;
        engine.rootContext()->setContextProperty("fontHelper", &helper);
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        if (engine.rootObjects().isEmpty())
            return -1;
    
        return app.exec();
    }
    
    #include "main.moc"
    

    main.qml

    import QtQuick 2.9
    import QtQuick.Window 2.2
    
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
    
        Text {
            id: txt
            font.family: "Helvetica"
            font.pointSize: 13
            font.bold: true
            text: "hello World"
            Component.onCompleted: txt.font = fontHelper.changeStretchFont(txt.font, 200)
        }
    }