Hiding Qt widget and keeping widget space

22,222

Solution 1

In Qt 5.2 it is possible to do the following:

QSizePolicy sp_retain = widget->sizePolicy();
sp_retain.setRetainSizeWhenHidden(true);
widget->setSizePolicy(sp_retain);

I earlier posted the same solution here:

How to make a Qt widget invisible without changing the position of the other Qt widgets?

(which seems to be a duplicate of this question).

Solution 2

Try to embed your widget into a QStackWidget having 2 pages: * your widget(s) on one page * another empty page

Set current qstackwidget page to the empty page when you want to hide your widget. And set it back to your main page to show back your widget(s).

Solution 3

I had the same issue.

I ended up adding a HorizontalSpacer (my layout was horizontal), which I initially set to 0-size and Fixed size policy. Then I used:

if (button_is_shown)
  ui.horizontalSpacer->changeSize(0,0, QSizePolicy::Fixed, QSizePolicy::Fixed);
else
  ui.horizontalSpacer->changeSize(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed);

To fill in the space. Similarly, you could resize the spacer to the size of the button and keep it as Fixed QSizePolicy.

Share:
22,222
Admin
Author by

Admin

Updated on February 13, 2020

Comments

  • Admin
    Admin over 4 years

    In a simple form I made a few buttons and put a horizontal layout. When mouse leaves the area one of the buttons, the last one, should be hidden. Using button->hide() it works, but all the buttons are rearranged by the layout manager. What I want is that all other buttons remain in their positions. I tried replacing the widget with a widget placeholder and swapping the button and placeholder hide()/show(), calling placeholder->resize(button->size()), but the layout manager doesn't respect the resize, and the placeholder is set with its minimum size. What is the best way to remove a widget and keep its space?