[Qt-interest] Height of QPushButton and QLineEdit different

Girish Ramakrishnan girish at forwardbias.in
Tue Jun 9 13:49:30 CEST 2009


Hi Oliver,

Oliver Demetz wrote:
> Hi all,
> 
> Simple example:
> 
>   QHBoxLayout * lay = new QHBoxLayout;
>   lay->addWidget(new QPushButton("Hello World"));
>   lay->addWidget(new QLineEdit("Foo Bar"));
>   this->setLayout(lay);
> 
> Executing this code, you will see, that the QLineEdit's
> height is smaller than the QPushButton's height.
> 
> I think it depends on the particular system, but on
> my Windows box here the button has height 28 whereas
> the lineedit only has 22 pixels.
> 
> *How can I adjust this???*
> 
> I tried several things:
> 
> (A:)  lineedit->setMinimumSize(button->height());
>     Didn't change anything.
> 

The height() is usually not a valid size until the layout has got a
chance to provide geometry to child widgets. Also, height() is the
actual height() that you see on the screen. You will have to manually
activate the layout to make height() something reasonable before the
widget is visible. But even then, after the widget is shown, it may get
a different height().

> (B:)  lineedit->setMinimumHeight(button->height());
>       lineedit->setMaximumHeight(button->height());
>      Leads to crap, the lineedit gets a huge height,
>      I don't know why.
> 

Same as above, height() won't be valid.

> (C:)  lineedit.setSizePolicy(
>                 lineedit.sizePolicy().horizontalPolicy(),
>                 QSizePolicy::Ignored);
>       The idea is to make the lineedit *expand* in the
>       layout in vertical direction, but this leads also
>       to a way too huge height
> 

The layout sets geometry based on widget's sizePolicy + sizeHint. The
push button has a fixed size policy in its vertical direction. This
means that if the sizeHint returned 80px vertically and the layout has
100 px of vertical space, the layout would resize the button only to
80px (and use alignment to figure out the position). When you set the
line edit's policy to ignored, the layout would make the line edit 100px
in height. See the problem?

One solution is to just
lineEdit->setFixedHeight(pushButton->sizeHint().height()); sizeHint will
take care of polishing, so you don't need ensurePolished().

> Why are the recommended heights for these two controls
> different at all?
> 

Girish



More information about the Qt-interest-old mailing list