[Interest] size policies, layouts, and size hints

Bo Thorsen bo at fioniasoftware.dk
Sun Mar 18 09:55:13 CET 2012


Den 17-03-2012 20:09, Joshua Grauman skrev:
> Hello all,
>
> Imagine a horizontal layout with 4 QLabels in it. The various QLabels have
> different amounts of text that can vary quite a bit and can be changed
> dynamically. I've been unable to get the horizontal layout/size policies
> to size the QLabels how I would like. What I would like is for the amount
> of 'extra' space to be divided up evenly between the QLabels. Any of the
> size policies I try end up giving extra space to the smaller QLabels
> *before* the bigger ones.

You can't do that with the normal layouts.

But it's pretty easy to implement this:

class LabelContainer : public QWidget {
...
protected:
   void resizeEvent() {
     space = totalLabelSizeHint() / labelCount;
     x = 0
     foreach (label) {
       label->setX(x)
       label->setWidth(label->sizeHint().width() + space)
       x += label->width()
     }
   }
};

You don't have to use layouts, sometimes it's easier to achieve special 
effects without them. But you have to think about how to handle cases 
where there isn't enough space for them. And implement sizeHint() etc. 
Using layouts is an easy way to do all this, but when they don't work 
for you, implement your own.

I wouldn't implement a QLayout subclass for this, unless it's a layout 
system you need in several cases.

Bo Thorsen,
Fionia Software.

-- 

Expert Qt and C++ developer for hire
Contact me if you need expert Qt help
http://www.fioniasoftware.dk



More information about the Interest mailing list