Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt widget with minimal size to fit all contents

Tags:

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..?

like image 296
rainer Avatar asked Dec 05 '12 19:12

rainer


People also ask

How do I change the size of a widget in Qt?

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!


1 Answers

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(); } 
like image 53
divanov Avatar answered Sep 18 '22 16:09

divanov