title: Centering a square qWidget in qt
body: <p>I am trying to solve a graphics problem using the latest version of Qt. The image below shows what I managed to get so far and I will use it to explain the expected result.</p>
  
  <p><a href="https://i.stack.imgur.com/byoy4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/byoy4.png" alt="The result of my work"></a></p>
  
  <p>I'm using a main vertical layout and within the biggest widget of the layout there is a horizontal layout with only one child: the square widget. The expected behavior would be of course to have the square widget centered horizontally and taking up the biggest space available. It is not required to use the same layout configuration, but the look of the interface should be the same.</p>
  
  <p>The image above has been obtained by setting a QSizePolicy of minimumExpanding for both vertical and horizontal to the square widget and by forcing it to be square with the following code:</p>
  
  <pre><code>void SquareWidget::resizeEvent(QResizeEvent *event) {
      //This is an override to the QWidget method
  
      QSize s = size();
  
      if (s.height()&lt;s.width()) {
          resize(s.height(), s.height());
      } else {
          resize(s.width(), s.width());
      }
      return;
  }
  </code></pre>
  
  <p>While trying to solve this problem I went through the documentation some of the answers on this website and I couldn't find a clear answer about how to do two tasks.</p>
  
  <p><strong>First problem: how to make the widget square and keep its aspect ratio?</strong></p>
  
  <p><a href="https://stackoverflow.com/questions/452333/how-to-maintain-widgets-aspect-ratio-in-qt">In this question</a></p>
  
  <p>it is said that the method heightForWidth () doesn't work in newer versions of qt, and after a test it doesn't work for me either. The above override of resizeEvent, on the other hand, causes recursion because there are calls to resize() (and as far as I understand the layout should handle the resizing).</p>
  
  <p><strong>Second problem: how to center the square?</strong></p>
  
  <p>I tried using the layout alignment properties (center horizontally and vertically) but they cause the widget size to be immutable.</p>
  
  <p>Maybe I am not understanding something about how Qt handles the widget placement. Any suggestion or clarification will be greatly appreciated.</p>