QML中的字体拉伸

问题描述 投票:1回答:1

我们正在转换一些较旧的QT小部件代码以使用QML,我找不到QFont::setStretch()操作的等效属性。

QML Font page仅显示系列,粗体,斜体,下划线,pointSize,pixelSize,weight,overline,strikeout,capitalization,letterSpacing,wordSpacing,kerning,preferShaping和hintingPreference。

这个字体选择是在Text对象中完成的,它的行如下:

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

是否无法在QML中设置伸展因子。我们正在使用Qt 5.6。

qt fonts qml qt5 stretch
1个回答
1
投票

不幸的是,这个属性没有暴露给QML,一个可能的解决方案是使用一个接收QFont的helper类,更改拉伸并返回新的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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.