Square QWidget - Height = Width

  • Is there a nice way to ensure that, when resized, a QWidget remains square (height = width)?

    I have a couple of QWidgets in a layout and when the layout size changes, I want to enforce this fixed size scheme.

  • Qt Champions 2017

    You can use
    int QWidget::heightForWidth(int w) const
    Those are virtuals so you need to subclass to use.

  • @mrjj Thanks for your comment.

    I've just implemented both the hasHeightForWidth (returning true) and the heightForWidth function (returning the width) - which I'm guessing is the correct way to do it.

    The outcome is ultimately the same - the widget is not square.

  • Qt Champions 2017

    Did you debug it ?
    Does it call your override ?

  • It does indeed, it calls both - many times

  • Qt Champions 2017


    HI you might also need sizeHint
    see this old sample
    (the QFrame)
    Sorry could not find newer.

  • I fought this fight in the past.
    heightForWidth determines the preferred height for width not the actual one. any layout is free to go beyond it.

    if you can live with setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); then use it, otherwise you'll need to create a custom layout

  • Qt Champions 2017

    oh so it can't work with layouts at all ?

    Thank you for enlightening us. I was pretty sure
    it would work with layouts also.

  • I must admit last time I looked at it I was still a n00b of Qt (even though little changed in the meantime). I vaguely remember having a layout with a Qt::Alignment private member. in the setGeometry I calculated the minimum of width and height, resized the widget according to that minimum and then placed it according to the alignment set. It supported only 1 item but it wasn't a big issue as you can combine layouts.

    If you are interested the code can be found here: header/source but, as I mentioned, it was a project I used to learn Qt so the code quality is surely below any reasonable standard

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.