PDA

View Full Version : QStackedWidget on QHBoxLayout



buster
4th December 2022, 21:37
I am trying to use QHBoxLayout for the following layout:

| m_widgetS | m_stackedWidget |

I want m_widgetS to be placed on the left hand side of a QStackedWidget populated with m_widgetA and later m_widgetB, m_widgetC, etc.
I am trying to create something similar to the KDE config dialogue, where I can switch widgets by selecting from a list on m_widgetS.
I am still using Qt 5 and my code looks like this:

m_widgetS = new WidgetS(this); // subclassed QWidget
m_widgetS->setStyleSheet("background-color: red"); // Make widgets visible

m_widgetA = new WidgetA(this); // subclassed QWidget
m_widgetA->setStyleSheet("background-color: blue");

m_stackedWidget = new QStackedWidget(this);
m_stackedWidget->addWidget(m_widgetA); // just one for now
m_stackedWidget->setCurrentWidget(m_widgetA);
m_stackedWidget->resize(400,600);

m_hBox = new QHBoxLayout(this);
m_hBox->addWidget(m_widgetS); // The static widget
m_hBox->addWidget(m_stackedWidget); // <-------
this->setLayout(m_hBox);

resize(600,600);

The strange thing is that the stacked widget covers the whole 600x600 area. If I comment out the line marked "// <-------" I can see the blue m_widgetA, now sized 400x600 and the red m_widgetS; that latter of size 600x600 and placed in front of the blue m_widgetA. The blue one is slightly higher than the red one (also strange), so I can see both. I have red the docs, but something must be wrong. Any ideas?

d_stranz
5th December 2022, 16:45
If I comment out the line marked "// <-------"

This is because you are creating all of your widgets as children of "this" (whatever it is), so they are all siblings. Once you start adding them to the HBox or stacked widget, you change the parent-child relationships so they are not siblings any more. The stacked widget and widget_s are still siblings, but now widget_a is a child of the stacked widget.

There could be several problems:

1 - Your widget_s does not have a minimum size, so the HBox thinks it can squeeze it to zero width.

2 - The stacked widget has a size policy that says it can expand to take up as much width as possible

3 - Your widget_a does not have a maximum size, so it can grow to match the stacked widget's width

4 - You have not set any "stretch" properties on the boxes within your HBox, the the HBox will size the widgets according to their preferences.

buster
6th December 2022, 16:35
I managed to fix it by setMinimumSize(). Thanks for the help.