3

I've been tracking down a bug that boils down to this - if you show an image label inside a scroll area, the label will not be resized to the image's size if QLabel::setPixmap() is called after QScrollArea::setWidget().

This example illustrates the problem, just replace /path/to/some/image.png with some real image on your computer:

QScrollArea *scrollArea = new QScrollArea;
QLabel *label = new QLabel(scrollArea);
scrollArea->setWidget(label);
label->setPixmap(QPixmap("/path/to/some/image.png"));
scrollArea->show();

If you swap the lines to call setPixmap() before setWidget(), the label will be properly resized.

Why does this happen, and how can I force the label to resize properly?

sashoalm
  • 75,001
  • 122
  • 434
  • 781

1 Answers1

3

Set your scroll area's widgetResizable property to true:

scrollArea->setWidgetResizable(true);
thuga
  • 12,601
  • 42
  • 52
  • OK, I tested it and it works, but why? The docs say if this property is true "the scroll area will automatically resize the widget in order to avoid scroll bars", which doesn't seem to be relevant to the problem. Also, the docs say that **regardless of this property** I can programmatically adjust the label, "and the scroll area will automatically adjust itself to the new size." So it should be working even without it. So what gives? – sashoalm Mar 26 '14 at 08:25
  • @sashoalm If you don't set the `widgetResizable` to true, the widget will keep its initial size until something else resizes it (for example you manually). – thuga Mar 26 '14 at 08:58
  • Doesn't `setPixmap()` also resize it? I assumed that it calls `resize()` somewhere in its code, though I tried tracing inside Qt, but couldn't find anything that looked like resizing. – sashoalm Mar 26 '14 at 09:02
  • @sashoalm No. You can test this. Create a `QLabel` with a parent. Set a pixmap to it, and don't add it to a layout. Run the program and you will notice it will be in its default size. – thuga Mar 26 '14 at 09:06
  • Thanks for the answer. I encountered another problem of the same nature, this time it's `ensureVisible()`. I've described it at http://stackoverflow.com/questions/22657386/qscrollareaensurevisible-and-qscrollareasetwidget, if you're interested to see it. – sashoalm Mar 26 '14 at 10:08