问题
I encountered another problem with QScrollArea
, after I got help for the previous one, which was somewhat similar.
The problem now is that ensureVisible()
does nothing if you create a scroll area and a label, set the label to be the scroll area's widget, and then load an image into the label - after 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->setWidgetResizable(true);
scrollArea->setWidget(label);
label->setPixmap(QPixmap("/path/to/some/image.png"));
label->setFixedSize(label->pixmap()->size());
scrollArea->ensureVisible(10000, 10000);
scrollArea->show();
If the setPixmap()
is called before setWidget()
, ensureVisible()
will work.
Also, the problem is reproducible even though I call setWidgetResizable()
and even setFixedSize()
.
Why does this happen, and is it possible to make ensureVisible()
work without changing the order of setWidget()
and setPixmap()
?
回答1:
When you call ensureVisible(10000, 10000);
the scrollArea hasn't adjusted the widget's size yet. That is why it won't work.
If you create a slot that calls ensureVisible
and use QTimer::singleShot
to call that slot with the timeout set to 0 (you can also use QMetaObject::invokeMethod
with queued connection), it will work, even if you set the scroll area's widget before you set the pixmap on the label.
What also works is, if you call ensureVisible
after you call show
. But this only works if your scrollArea
is a top level window. If you embed it to a widget, it will not work.
来源:https://stackoverflow.com/questions/22657386/qscrollareaensurevisible-and-qscrollareasetwidget