PDA

View Full Version : Removing the last item in a layout or inserting a widget at the second-to-last spot?



ComServant
2nd April 2012, 02:04
I have a QScrollArea, and I add widgets to the scroll area as my program runs. I want the order of the widgets to be in the order I add them (first added should be at the top, second added should be next, and so on).

I want all the widgets pushed to the top of the QScrollArea, so I call layout->stretch().

The problem is, how can I insert a new widget at the second to last position of the QScrollArea, so it's after my previous widgets, but before the stretch?
Alternatively, how can I delete the stretch, so I can add the widget and then re-add the stretch?

I've tried messing with this numerous times in the past, and I always end up using some hacky way to get it working. What's the best way to do this?
I'm aware of insertWidget, but I can't figure out how to get the index of the stretch so I can insert before it.

Any hints?

ChrisW67
2nd April 2012, 05:32
QWidget *newWidget = ...;

layout->insertWidget(layout->count() - 1, newWidget);

seems the obvious approach.

You can probably do away with the spacer item (I assume) altogether using the layout's size constraint.

ComServant
2nd April 2012, 23:53
Hey, thanks alot. I've checked for a layout->count() type function and missed it. I was looking for a size(), I've been working with the C++ standard library too long. =)
I also thought of widget->children().count(), but the parent might have non-layout children, and the layout itself doesn't own the children it has.

If I altered the layout's size constraint, and only have, say, 3 objects in the layout, if those widgets are less than the QScrollArea size (fixed minimum size), the QScrollArea would make the widget hover in the center, instead of at the top... or so I assumed, but another perusal of the documentations says otherwise (QScrollAreas have alignments, which I forgot about, plus it defaults to top-left and not the center).