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

后端 未结 6 2008
长情又很酷
长情又很酷 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:13

    I have polished this missing subclass of QLabel. It is awesome and works well.

    aspectratiopixmaplabel.h

    #ifndef ASPECTRATIOPIXMAPLABEL_H
    #define ASPECTRATIOPIXMAPLABEL_H
    
    #include 
    #include 
    #include 
    
    class AspectRatioPixmapLabel : public QLabel
    {
        Q_OBJECT
    public:
        explicit AspectRatioPixmapLabel(QWidget *parent = 0);
        virtual int heightForWidth( int width ) const;
        virtual QSize sizeHint() const;
        QPixmap scaledPixmap() const;
    public slots:
        void setPixmap ( const QPixmap & );
        void resizeEvent(QResizeEvent *);
    private:
        QPixmap pix;
    };
    
    #endif // ASPECTRATIOPIXMAPLABEL_H
    

    aspectratiopixmaplabel.cpp

    #include "aspectratiopixmaplabel.h"
    //#include 
    
    AspectRatioPixmapLabel::AspectRatioPixmapLabel(QWidget *parent) :
        QLabel(parent)
    {
        this->setMinimumSize(1,1);
        setScaledContents(false);
    }
    
    void AspectRatioPixmapLabel::setPixmap ( const QPixmap & p)
    {
        pix = p;
        QLabel::setPixmap(scaledPixmap());
    }
    
    int AspectRatioPixmapLabel::heightForWidth( int width ) const
    {
        return pix.isNull() ? this->height() : ((qreal)pix.height()*width)/pix.width();
    }
    
    QSize AspectRatioPixmapLabel::sizeHint() const
    {
        int w = this->width();
        return QSize( w, heightForWidth(w) );
    }
    
    QPixmap AspectRatioPixmapLabel::scaledPixmap() const
    {
        return pix.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    }
    
    void AspectRatioPixmapLabel::resizeEvent(QResizeEvent * e)
    {
        if(!pix.isNull())
            QLabel::setPixmap(scaledPixmap());
    }
    

    Hope that helps! (Updated resizeEvent, per @dmzl's answer)

提交回复
热议问题