[Qt-interest] Squeezing/Shrinking widgets after removing children

Frank Hemer frank at hemer.org
Thu Aug 13 17:35:54 CEST 2009


On Thursday 13 August 2009 17:15:52 Daniel Albuschat wrote:
> Hi there,
>
> you can resize a widget to it's minimum required size by calling
> resize(0, 0). I noticed, however, that, right after removing a widget
> from it, the widget is not updated and the following call to resize(0,
> 0) resizes the widget to the size *including* the previously removed
> widget. I guess that's because the actual removing only happens when
> the event queue is processed.
>
> I've created a blog-post with a detailed explanation and test-case here:
> http://daniel-albuschat.blogspot.com/2009/08/shrinking-qt-widgets-to-minimu
>m-needed.html
>
> Is this correct? Is there some cleaner way around this than
> QTimer::singleShot() or QApplication::processEvents()?
>
> I find this pretty awkward and stumbled upon this problem a lot in the
> past, but usually just avoided it by doing something different.

I work with dynamic dialogs that are created at runtime and often change their 
content so I had the requirement to find a solution for this problem.

Finally I found this to work:

In the Dialog itself there is a method I call at any time the layout was 
changed to do a complete relayout like this:

void FormDialog::resetLayout () {
   QList <QWidget *> widgets = qFindChildren <QWidget *> (this);
   QEvent e (QEvent::LayoutRequest);
   foreach (QWidget * w, widgets) {
      QCoreApplication::sendEvent (w, &e);
      w->updateGeometry ();
   }
   QCoreApplication::sendEvent (this, &e);
   updateGeometry ();

   //resize dlg to its content
   QRect currentGeometry = geometry ();
   QSize sizeHint = layout ()->sizeHint ();

   QPoint p = currentGeometry.center ();
   currentGeometry.setWidth (sizeHint.width ());
   currentGeometry.setHeight (sizeHint.height ());
   currentGeometry.moveCenter (p);
   setMinimumSize (QSize (0, 0));//reset a previously set minimum size!
   setGeometry (currentGeometry);
}

I have no idea whether this approach works under all circumstances as it is 
heavily dependent on a valid sizeHint of its elements though ...

Hope that helps
Frank



More information about the Qt-interest-old mailing list