Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

后端 未结 6 2029
长情又很酷
长情又很酷 2020-11-28 03:35

I use a QLabel to display the content of a bigger, dynamically changing QPixmap to the user. It would be nice to make this label smaller/larger depending on the space availa

6条回答
  •  情书的邮戳
    2020-11-28 04:26

    I just use contentsMargin to fix the aspect ratio.

    #pragma once
    
    #include 
    
    class AspectRatioLabel : public QLabel
    {
    public:
        explicit AspectRatioLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
        ~AspectRatioLabel();
    
    public slots:
        void setPixmap(const QPixmap& pm);
    
    protected:
        void resizeEvent(QResizeEvent* event) override;
    
    private:
        void updateMargins();
    
        int pixmapWidth = 0;
        int pixmapHeight = 0;
    };
    
    #include "AspectRatioLabel.h"
    
    AspectRatioLabel::AspectRatioLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f)
    {
    }
    
    AspectRatioLabel::~AspectRatioLabel()
    {
    }
    
    void AspectRatioLabel::setPixmap(const QPixmap& pm)
    {
        pixmapWidth = pm.width();
        pixmapHeight = pm.height();
    
        updateMargins();
        QLabel::setPixmap(pm);
    }
    
    void AspectRatioLabel::resizeEvent(QResizeEvent* event)
    {
        updateMargins();
        QLabel::resizeEvent(event);
    }
    
    void AspectRatioLabel::updateMargins()
    {
        if (pixmapWidth <= 0 || pixmapHeight <= 0)
            return;
    
        int w = this->width();
        int h = this->height();
    
        if (w <= 0 || h <= 0)
            return;
    
        if (w * pixmapHeight > h * pixmapWidth)
        {
            int m = (w - (pixmapWidth * h / pixmapHeight)) / 2;
            setContentsMargins(m, 0, m, 0);
        }
        else
        {
            int m = (h - (pixmapHeight * w / pixmapWidth)) / 2;
            setContentsMargins(0, m, 0, m);
        }
    }
    

    Works perfectly for me so far. You're welcome.

提交回复
热议问题