2

I'm trying to implement a scalable image widget with qt creator that will preserve the aspect ratio of the image. All the examples or posts I've found suggest extending QLabel and reimplementing resizeEvent. This is what I've done and it almost works, but for a few problems.

  1. When the main window first opens the images grow slightly and expand the size of the main window (this is not too big a problem).

  2. When I maximize the window all the images scale up, but when I unmaximize the window the images fail to scale back down.

I have tried changing the resizeEvents of both the QLabel subclass (called ClickableImage) and the parent widget that holds the layout containing the ClickableImage. Here is some of the relevant code.

void ClickableImage::resizeEvent(QResizeEvent *e)
{
    qDebug() << "Resizing : " << ticker;
    ticker++;

    int w = e->size().width();
    int h = e->size().height();

    qDebug() << "W : " << w;
    qDebug() << "H : " << h;

    image = QPixmap(fname);
    image = image.scaled(w-7, h-7, Qt::KeepAspectRatio);
    setPixmap(image);
}

Also, I've read the following sources,

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

https://docs.huihoo.com/qt/4.2/desktop-screenshot.html

Thanks.

mavroprovato
  • 8,023
  • 5
  • 37
  • 52
  • you have a bug in your code, replace the -7 with some multiplication – Martin Jun 18 '12 at 08:29
  • I'm sorry, I don't understand. The -7 is to keep the pixmap inside the bounds of the QLabel. What should I be multiplying by? – user1462348 Jun 18 '12 at 23:59
  • It's I who should be sorry, I misread your code and thought you were sca,ing using the 7. You're perfectly right – Martin Jun 19 '12 at 14:28

1 Answers1

0

I have four things that you should try. If you put a larger code example, I would maybe try it for you, but here is what I have for you:

  1. You probably need to call adjustSize() at the end of the resize event. You probably don't need an update() call, but you could try putting one in there and see if it makes a difference.

  2. The minimize event should be the same as a hideEvent(), so put some of your image scaling in there too, if you want it to change the image size on the minimize.

  3. The documentation on the Window and Dialog Widgets may help with some of the sizing, but it may also be part of the recursive nature of setting the size of the something in the widget when it gets resized.

  4. An alternative to all this is to let the widget figure out the resizing for you. QLabel has an option to have it scale its contents based on the size it is allowed to take up, so if you create a QLabel, set its pixmap and set the scale contents property, then it will do the fast scaling for you automatically on the resize. You probably would still need to scale it down for the minimize.

Hope that helps. Let me know if you are still having issues.

phyatt
  • 18,472
  • 5
  • 61
  • 80