I'd like to have a QWidget
instance that uses a QHBoxLayout
and (ideally automatically, but upon calling some function is fine too) resizes horizontally to fit its contents. Horizontal resizing is enough since all widgets, including the container itself, will have the same height.
The use case is the following: The widget, let's call it container, is floating, i.e. not part of any layout. A user should be able to add further widgets with a fixed size (by calling a function) to the container's layout, upon which the container grows to fit its new contents. The user should also be able to remove a previously added widget, upon which the container shrinks again. The container will not be created until the first widget is inserted and deleted when the last one is removed, i.e. it will always contain at least one widget.
An example: after adding the first widget, the container looks like this, with |
being its left/right borders:
|<1st widget>|
After adding another one, it looks like this:
|<1st widget> <2nd, longer widget>|
After removing the first widget, it looks like this:
|<2nd, longer widget>|
I suspect that this should be kind of simple, but I got lost somewhere inbetween container's sizeHint
, sizePolicy
, adjustSize()
, and its layout's sizeContraint
as well as several attempts with explitely setting the size and forcing updates and essentially got nowhere (i.e. the container not resizing at all, the container only growing but not shrinking, etc). I suspect that I must have missed something kind of obvious..?
If the width won't change afterwards, you can use setFixedWidth : widget->setFixedWidth(165); Similarly, to change the height without changing the width, there is setFixedHeight . Never use fixed width!
Your guess is right. One has to set size policies for widgets in a layout. First widget should have QSizePolicy::Minimum
and second one should have QSizePolicy::Expanding
to achieve a desired effect. Here is a sample application:
#include <QtGui> int main(int argc, char *argv[]) { QApplication a(argc, argv); QPushButton *button1 = new QPushButton("Hello"); button1->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred); QObject::connect(button1, SIGNAL(clicked(bool)), button1, SLOT(hide())); QPushButton *button2 = new QPushButton("World"); button2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); QObject::connect(button2, SIGNAL(clicked(bool)), button2, SLOT(hide())); QHBoxLayout *layout = new QHBoxLayout(); layout->addWidget(button1); layout->addWidget(button2); QWidget main; main.setLayout(layout); main.show(); return a.exec(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With