【问题标题】:How to set dynamic QFont size?如何设置动态 QFont 大小?
【发布时间】:2018-01-03 09:16:02
【问题描述】:

我遇到了 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 类。

【问题讨论】:

  • 您能展示一下您是如何使用 Scale 的吗?你的应用程序是 QML 还是 C++?
  • @eyllanesc 请查看编辑。
  • 您要更改什么字体?
  • Draw_on_qimage 类中有一个paint 函数。这使用了一些文本。我想控制它的大小。 @eyllanesc
  • Draw_on_qimage 继承什么类,继承自 qquickpainteditem?

标签: c++ qt qml qfont qfontmetrics


【解决方案1】:

最简单的方法是将 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 是建立字体大小和窗口大小之间关系的函数。

【讨论】:

  • 感谢您的努力。您的示例的目的是展示如何将屏幕的高度和宽度传递给 cpp 以进行字体调整?
  • @Aquarius_Girl 不,这表明你可以从 QML 设置字体大小。
  • @Aquarius_Girl 看下面的例子,如果你手动改变窗口大小你会看到字体大小改变了github.com/eyllanesc/stackoverflow/tree/master/48074369
猜你喜欢
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 2012-05-18
  • 2019-11-25
  • 1970-01-01
  • 2013-09-22
相关资源
最近更新 更多