1

I have a QLabel that contains an image. I need to ensure that the image allways takes 100% of the QLabel width, but preserving aspect ration is just as important. This means I also need to increase QLabel height so that the image fits. Like on this image, the height must be fit:

image description

I Qt designer I see no way to specify preferred aspect ratio, so I just tried to override resize event and try to force correct height upon resize:

void QPictureLabel::resizeEvent(QResizeEvent *event)
{
    qDebug()<<"Resized.";
    // Current image width in pixels
    float pw = myPixmap.width();
    // current label width in pixels
    float my_width = width();
    // ratio of label and image width can decide the new required label height
    float new_h = (my_width/pw)*myPixmap.height();
    // This is an attempt to prevent endless loop... didn't work out
    if(new_h!=height()) {
        // Force new height (that works)
        resize(my_width, new_h);
        // Tell the layout to move other elements (that doesn't work at all!)
        updateGeometry();
    }
}

Before adding the updateGeometry call it just looked like this:

image description

As you can see (I highlighted it with red frame), the label indeed expanded as necessary. But other widgets do not care about that.

I added updateGeometry call, but the result was endless loop for some reason. I need the correct way to inform the layout that QLabel requires more space.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • 2
    have you tried qt's `heightForWidth`? Docs here - http://doc.qt.io/qt-4.8/qwidget.html#heightForWidth – Shf Dec 15 '15 at 16:10
  • There are a couple of older questions asking essentially this. See https://stackoverflow.com/questions/30005540/keeping-the-aspect-ratio-of-a-sub-classed-qwidget-during-resize, and https://stackoverflow.com/questions/452333/how-to-maintain-widgets-aspect-ratio-in-qt?lq=1 – sashoalm Dec 15 '15 at 16:11
  • @Shf `heightForWidth` no longer works in new versions of Qt. – Tomáš Zato Dec 16 '15 at 09:55
  • @TomášZato , huh? Works for my project with qt 5.5.1 – Shf Dec 16 '15 at 11:48
  • @TomášZato , also, did you try to resize not label with image, but just image itself? With scaled and keepAspectRatio? Take a look at this answer - http://stackoverflow.com/questions/19715232/qt-how-do-i-resize-an-image-and-maintain-its-proportions or even better solution (to reimplement sizehint for you label, so that layout will know correct size) - this answer - http://stackoverflow.com/questions/14107144/how-do-i-make-an-image-resize-to-scale-in-qt – Shf Dec 16 '15 at 11:51

1 Answers1

-1

but the result was endless loop for some reason

This is documented, read documentation on resizeEvent(). Shf's solution should work for you.

DmitryARN
  • 648
  • 3
  • 10
  • I guess you're right, but this is not a way to post helpful answer. Keep such things in comments, especially since you're not adding much new information. – Tomáš Zato Dec 15 '15 at 17:44