nandaloo
nandaloo

Reputation: 1027

Qt - Centering 'MinimumExpanding' widgets in a layout

I got a QHBoxLayout, which contains 2 QWidgets. Both of these QWidgets have a fixed aspect ratio (square) and have a minimum expanding QSizePolicy by doing this:

QSizePolicy policy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
policy.setHeightForWidth(true);
setSizePolicy(policy);

and implementing heightForWidth like this:

virtual int heightForWidth (int w) const override {
    return w;
}

Now, I would like those widgets to be centered in my layout. Thus I add them to the layout like this:

layout->addWidget(widget1, 0, Qt::AlignCenter);

However, like this they end up at their preferred size, but do not taking up all space that's available. Why is that? It seems like Qt::AlignCenter overwrites my SizePolicy?!

In contrast using Qt::AlignVCenter will actually make them occupy all space available. How does that fit together?

Thanks you!

Upvotes: 1

Views: 1090

Answers (1)

Marek R
Marek R

Reputation: 38209

Please note that Qt::AlignCenter = Qt::AlignVCenter + Qt::AlignHCenter.
Note that if you set alignment of any kind then you are saying that you want preferred size (what sizeHint returns) but object should positioned in proper way. When you want to fill whole space then alignment has no sense.
So I suspect that behavior you have described is designed like that.

Digression: Note that QGraphicsWidgets have 3 sizeHints: minimum, preferred and maximum, so in this case when some alignment expanding size policy still applies since there is maximum size widget can occupy.

Upvotes: 1

Related Questions