簡體   English   中英

如何設置動態QFont大小?

[英]How to set dynamic QFont size?

我遇到了 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 是建立字體大小和窗口大小之間關系的函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM