简体   繁体   中英

How to set dynamic QFont size?

I came across QFontMetrics? http://doc.qt.io/qt-5/qfontmetrics.html
This gives the height and width of the present font.

I need to run my application with full screen mode on on different monitors for which I am using Scale class. http://doc.qt.io/qt-5/qml-qtquick-scale.html

That returns the height and width of the current screen.

Is there a way to use QFontMetrics or anything else to change the font size according to the monitor size?

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 is a cpp class.

The easiest way is to set QFont as Q_PROPERTY of your item so you can set it from 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

To set its size we use the pointSize property of QFont:

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
    }
}

Where some_function is the function that establishes the relationship between the font size and the size of the window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM