QML中的字体拉伸 [英] Font stretching in QML
问题描述
我们正在将一些较旧的 QT 小部件代码转换为使用 QML,但我找不到 QFont::setStretch()
操作.
We are converting some older QT widget code to use QML and I cannot find the equivalent property for the QFont::setStretch()
operation.
QML 字体页面仅显示系列、粗体、斜体、下划线、pointSize、pixelSize、粗细、上划线、删除线、大写、letterSpacing、wordSpacing、字距调整、preferShaping 和hintingPreference.
The QML Font page shows only family, bold, italic, underline, pointSize, pixelSize, weight, overline, strikeout, capitalization, letterSpacing, wordSpacing, kerning, preferShaping and hintingPreference.
这个字体选择是在一个 Text
对象中完成的,如下所示:
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
}
有没有办法在 QML 中设置拉伸因子.顺便说一下,我们使用的是 Qt 5.6.
Is there no way to set the stretch factor in QML. We're using Qt 5.6 by the way.
推荐答案
不幸的是,这个属性没有暴露给 QML,一个可能的解决方案是使用一个辅助类来接收 QFont,改变拉伸并返回新的 QFont.
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)
}
}
这篇关于QML中的字体拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!