Font stretching in QML

旧城冷巷雨未停 提交于 2021-02-10 18:55:12

问题


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.


回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/55348741/font-stretching-in-qml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!