A QLayout
always tries to use the whole available space of the QWidget
. But, sometimes, you want it to keep it's minimal size and center itself on the widget...because you feel like it looks better (if the layout only contains items that does not make sense to be displayed bigger than their default size: QLabel
, QPushButton
and stuffs like that).
I had this problem hundreds of times in the past, and I'm always adding stupid QSpacerItems everywhere to fix that. I'm wondering if there could be a better solution.
I isolated the problem as an illustration:
#include <QApplication>
#include <QDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QSpacerItem>
class MainFrame : public QDialog
{
public:
MainFrame() : QDialog(NULL)
{
QHBoxLayout* theLayout = new QHBoxLayout();
setLayout( theLayout );
// don't want to add spacers all the time!
//theLayout->addSpacerItem( new QSpacerItem( 10, 10, QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) );
theLayout->addWidget( new QLabel( "A text", this ) );
theLayout->addWidget( new QPushButton( "A button", this ) );
// don't want to add spacers all the time!
//theLayout->addSpacerItem( new QSpacerItem( 10, 10, QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) );
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainFrame w;
w.resize(400,400);
w.show();
return a.exec();
}
Without the spacers, here's how it looks like:
I hate this display, on larger QWidget
your eyes have to go all around the widget to find the relevant information.
With spacers, here's how it looks like:
I like it much better.
Is there a way to do this without adding the spacers? It's a pain adding them and always having to specify all those arguments (defaults won't do what you want...).
I tried to use QLayout::setSizeConstraint
with no success. Does not appear to be meant to do this.