Qt layouts - Keep widget aspect ratio while resizing [duplicate]

谁都会走 提交于 2019-12-05 13:24:16

Your approach could work if this group box was inside vertical layout.

As name says hasHeightForWidth is well defined when height depends on width (this was designed for text wrapping), not another way around (your case).

What you can do? Try this (I've implemented something similar for QGraphicsWidget and it was working quite well):

QSize GroupBoxHFW::sizeHint() const {
    QSize s = size();
    lastHeight = s.height();
    s.setWidth((s.height()*16)/9);
    s.setHeight(QGroupBox::sizeHint().height());
    return s;
}

void GroupBoxHFW::resizeEvent(QResizeEvent * event) {
    QGroupBox::resizeEvent(event);

    if (lastHeight!=height()) {
        updateGeometry(); // it is possible that this call should be scheduled to next iteration of event loop
    }
}

Small off topic:
If I would do that I would try implement this functionality by subclass a QLayout and not as a subclass of some QWidget. This way this it could be used multiple times for different widgets.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!