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

    Hi
    You can use
    http://doc.qt.io/qt-5/qwidget.html#hasHeightForWidth
    and
    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

    @webzoid
    Did you debug it ?
    Does it call your override ?



  • It does indeed, it calls both - many times


  • Qt Champions 2017

    @webzoid

    HI you might also need sizeHint
    see this old sample
    https://doc.qt.io/archives/qq/qq04-height-for-width.html
    (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

    @VRonin
    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


Log in to reply
 

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