如何设置动态 QFont 大小

How to set dynamic QFont size?

本文关键字:动态 QFont 大小 设置 何设置      更新时间:2023-10-16

我遇到了QFontMetrics?
http://doc.qt.io/qt-5/qfontmetrics.html这给出了当前字体的高度和宽度。

我需要在使用 Scale 类的不同显示器上以全屏模式运行我的应用程序。 http://doc.qt.io/qt-5/qml-qtquick-scale.html

这将返回当前屏幕的高度和宽度。

有没有办法使用 QFontMetrics 或其他任何东西根据显示器大小更改字体大小?

ApplicationWindow
{
    id: head
    visible: true
    width:  Screen.width
    height: Screen.height
    title: "Novus Pilot"
    property var id: 0;
    Draw_on_qimage
    {
        id: draw_on_qimage
        anchors.fill: parent
        parent: image
        scaleX: head.width / 640
        scaleY: head.height / 480
    }
}

Draw_on_qimage是一个CPP类。

最简单的方法是将QFont设置为项目的Q_PROPERTY,以便您可以从QML进行设置:

#ifndef DRAWITEM_H
#define DRAWITEM_H
#include <QPainter>
#include <QQuickPaintedItem>
class DrawItem : public QQuickPaintedItem
{
    Q_OBJECT
    Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged)
public:
    DrawItem(QQuickItem *parent = Q_NULLPTR):QQuickPaintedItem(parent){}
    void paint(QPainter *painter){
        painter->setFont(mFont);
        painter->drawText(boundingRect(), "Hello");
    }
    QFont font() const{
        return mFont;
    }
    void setFont(const QFont &font){
        if(mFont == font)
            return;
        mFont = font;
        emit fontChanged();
        update();
    }
signals:
    void fontChanged();
private:
    QFont mFont;
};
#endif // DRAWITEM_H

为了设置它的大小,我们使用 QFont 的 pointSize 属性:

DrawItem
{
    id: draw_on_qimage
    anchors.fill: parent
    font.pointSize: some_function(head.width, head.height)
    transform: Scale {
        xScale: head.width / 640
        yScale: head.height / 480
    }
}

其中some_function是建立字体大小和窗口大小之间关系的函数。