0

I am dynamically creating a QLabel named label (that has a QPixmap) inside a QHBLayout named layout inside a parent QWidget named by this such that the QLabel image resizes with parent this but maintains the original image aspect ratio.

What I am doing now is the following:

QHBoxLayout* layout = new QHBoxLayout(this);
label = new QLabel(str, this); /* This Label is my concern */
label->setAlignment(Qt::AlignLeft|Qt::AlignVCenter);
layout->addWidget(label);
layout->setAlignment(Qt::AlignCenter);
this->setLayout(layout);
layout->setContentsMargins(0,0,0,0);
layout->setSpacing(0);
label->setScaledContents(true);
label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

After searching online and as suggested in the accepted answer in Qt layouts - Keep widget aspect ratio while resizing, I even tried creating my own MyLabel class and defining sizeHint() and resizeEvent(QResizeEvent* event) as follows:

QSize MyLabel::sizeHint() const
{
    QSize s = size();
    lastHeight = s.height();
    lastWidth = s.width();
    QSize qs = QLabel::sizeHint();
    float ratio = std::min(((float)qs.width())/lastWidth, ((float)qs.height())/lastHeight);
    s.setWidth(lastWidth*ratio);
    s.setHeight(lastHeight*ratio);
    return s;
}

void MyLabel::resizeEvent(QResizeEvent* event)
{
    QLabel::resizeEvent(event);
    if(lastHeight!=height())
    {
        updateGeometry();
    }
}

But the label image still resizes without maintaining aspect ratio.

What am I missing here?

Any help will be highly appreciated. Thanks in advance.

Community
  • 1
  • 1

2 Answers2

0

Try using the subclass of QLabel listed here:

https://stackoverflow.com/a/22618496/999943

Hope that helps.

Community
  • 1
  • 1
phyatt
  • 18,472
  • 5
  • 61
  • 80
  • This class works. On comparing my defined `MyLabel` and this `AspectRatioPixmapLabel` class, it turns out that the main culprit is the use of the function call as `setScaledContents(true);`. It must be set as `setScaledContents(false);`. So I am proposing to update your helpful answer. –  Apr 18 '17 at 08:47
0

Try to resize your image instead of QLabel. E.g. by hangling parent widget's resizeEvent and doing something like:

const QPixmap* pixmap = label->pixmap();
if (pixmap->width() >= newGeometry.width())
{
    QPixmap scaledPixmap = pixmap->scaledToWidth(newWidth, Qt::SmoothTransformation);
    label->setPixmap(scaledPixmap);
}
Max Pashkov
  • 404
  • 1
  • 3
  • 12