How is it possible to maintain widgets aspect ratio in Qt and what about centering the widget?
You don't have to implement your own layout manager. You can do with inheriting QWidget
and reimplementing
int QWidget::heightForWidth( int w ) { return w; }
to stay square. However, heightForWidth()
doesn't work on toplevel windows on X11, since apparently the X11 protocol doesn't support that. As for centering, you can pass Qt::AlignCenter
as the third parameter of QBoxLayout::addWidget()
or the fifth parameter of QGridLayout::addWidget()
.
Note: In newer versions of Qt at least, QWidget does not have the heightForWidth
or widthForHeight
anymore (so they cannot be overriden), and therefore setWidthForHeight(true)
or setHeightForWidth(true)
only have an effect for descendants of QGraphicsLayout.
widthForHeight
method. –
Rabid heightForWidth
works for any widget. However, widthForHeight
is only for subclasses of QGraphicLayout
(doc.qt.io/qt-6/qsizepolicy.html#setHeightForWidth). –
Deoxidize The right answer is to create your custom layout manager. That is possible by subclassing QLayout.
Methods to implement when subclassing QLayout
- void addItem(QLayoutItem* item);
- Adds item to layout.
- int count() const;
- Returns the item count.
- QLayoutItem* itemAt(int index) const;
- Returns item reference at index or 0 if there's none.
- QLayoutItem* takeAt(int index);
- Takes and returns item from the layout from index or returns 0 if there is none.
- Qt::Orientations expandingDirections() const;
- Returns the layouts expanding directions.
- bool hasHeightForWidth() const;
- Tells if the layout handles height for width calculation.
- QSize minimumSize() const;
- Returns the layouts minimum size.
- void setGeometry(const QRect& rect);
- Sets the geometry of the layout and the items inside it. Here you have to maintain the aspect ratio and do the centering.
- QSize sizeHint() const;
- Returns the preferred size for the layout.
Further reading
QLayout
, but the functions you quote are from QLayoutItem
, which just calls the corresponding functions from QWidget
. So what can inheriting QLayout
give you that QWidget
itself can't? –
Coon Calling resize()
from within resizeEvent()
has never worked well for me -- at best it will cause flickering as the window is resized twice (as you have), at worst an infinite loop.
I think the "correct" way to maintain a fixed aspect ratio is to create a custom layout. You'll have to override just two methods, QLayoutItem::hasHeightForWidth()
and QLayoutItem::heightForWidth()
.
setMinimumHeight
inside the resizeEvent
function, my call stack is huge when my program crashes sometimes when I resize it. Sadly, I am looking into creating my own layout. –
Virelay I too was trying to achieve the requested effect: a widget that keeps a fixed aspect ratio while staying centred in its allocated space. At first I tried other answers from this question:
- implementing
heightForWidth
andhasHeightForWidth
as suggested by marc-mutz-mmutz simply didn't work for me. - I briefly looked at implementing a custom layout manager, but all Bleadof's links were dead, and when I found the documentation and read through it, it looked way too complicated for what I was trying to achieve.
I ended up creating a custom widget that responds to resizeEvent
and uses setContentsMargin
to set margins such that the remaining content area keeps the desired ratio.
I found I also had to set the widget's size policy to QSizePolicy::Ignored
in both directions to avoid odd resizing issues resulting from the size requests of child widgets—the end result is that my widget accepts whatever size its parent allocates to it (and then sets its margins as described above to keep the desired aspect ratio in its content area).
My code looks like this:
from PySide2.QtWidgets import QWidget, QSizePolicy
class AspectWidget(QWidget):
'''
A widget that maintains its aspect ratio.
'''
def __init__(self, *args, ratio=4/3, **kwargs):
super().__init__(*args, **kwargs)
self.ratio = ratio
self.adjusted_to_size = (-1, -1)
self.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored))
def resizeEvent(self, event):
size = event.size()
if size == self.adjusted_to_size:
# Avoid infinite recursion. I suspect Qt does this for you,
# but it's best to be safe.
return
self.adjusted_to_size = size
full_width = size.width()
full_height = size.height()
width = min(full_width, full_height * self.ratio)
height = min(full_height, full_width / self.ratio)
h_margin = round((full_width - width) / 2)
v_margin = round((full_height - height) / 2)
self.setContentsMargins(h_margin, v_margin, h_margin, v_margin)
(Obviously, this code is in Python, but it should be straightforward to express in C++ or your language of choice.)
In my case overriding heightForWidth() doesn't work. And, for someone, it could be helpful to get working example of using resize event.
At first subclass qObject to create filter. More about event filters.
class FilterObject:public QObject{
public:
QWidget *target = nullptr;//it holds a pointer to target object
int goalHeight=0;
FilterObject(QObject *parent=nullptr):QObject(parent){}//uses QObject constructor
bool eventFilter(QObject *watched, QEvent *event) override;//and overrides eventFilter function
};
Then eventFilter function. It's code should be defined outside of FilterObject definition to prevent warning. Thanks to this answer.
bool FilterObject::eventFilter(QObject *watched, QEvent *event) {
if(watched!=target){//checks for correct target object.
return false;
}
if(event->type()!=QEvent::Resize){//and correct event
return false;
}
QResizeEvent *resEvent = static_cast<QResizeEvent*>(event);//then sets correct event type
goalHeight = 7*resEvent->size().width()/16;//calculates height, 7/16 of width in my case
if(target->height()!=goalHeight){
target->setFixedHeight(goalHeight);
}
return true;
};
And then in main code create FilterObject and set it as EventFilter listener to target object. Thanks to this answer.
FilterObject *filter = new FilterObject();
QWidget *targetWidget = new QWidget();//let it be target object
filter->target=targetWidget;
targetWidget->installEventFilter(filter);
Now filter will receive all targetWidget's events and set correct height at resize event.
© 2022 - 2024 — McMap. All rights reserved.
sizePolicy
thathasHeightForWidth() == true
, and the layout will often give the widget more width or height that it asks for, but that's the layout trying to satisfy the constraints. You will get the same effect with theQLayoutItem
solution, as they're equivalent (cf.QWidgetLayoutItem
). – Coon