Important: Please read the Qt Code of Conduct -

How to keep child qwidget aspect ratio.

  • I know this question has been answered many times, but there is no one satisfied to me,

    I hope that the aspect = width/height == 1.5, and the code is below.

    QSize size = widget->size();
    float aspect = 1.5;
    int hintHeight = sz.height() * aspect;
    if(size.width() > hintHeight ) {
      size.rwidth() = hintHeight ;
    } else {
      size.rheight() = size.width() / aspect;

    I have try this in resizeEvent() but the resize() will cause infinity loop, and the heightForWidth(int w) solution can't be applied in this situation, since I need the height depend on width when height is longer than width, and width depend on height when width is longer than height.
    I need that work like the gif in the link

  • Lifetime Qt Champion


    That links is not a git but a gif. What exactly is your child widget ?

  • Sorry, I typed wrong, I mean I need the child widget could scale like the picture in the gif.

  • Lifetime Qt Champion

    Can you show how you are handling this currently ?

  • The gif is a photo viewer software in win10, I need a qt widget work like that, I haven't handle this yet.

  • I implemented this back in the days when I was learning Qt (so be aware the code quality is probably below par and might be bugged):

  • Thank you, that's work!

Log in to reply