Center and Resize the MainWindow on the current screen

The following method computes the final size of the window setting it so it covers the 90% of the whole screen available space, and then centers it (left-to-right flow):

  1. void MainWindow::centerAndResize(){
  2.     // get the dimension available on this screen
  3.     QSize availableSize = qApp->desktop()->availableGeometry().size();
  4.     int width  = availableSize.width();
  5.     int height = availableSize.height();
  6.     qDebug() << "Available dimensions " << width << "x" << height;
  7.     width  *= 0.9;   // 90% of the screen size
  8.     height *= 0.9;  // 90% of the screen size
  9.     qDebug() << "Computed dimensions " << width << "x" << height;
  10.     QSize newSize( width, height );
  11.  
  12.     setGeometry(
  13.                 QStyle::alignedRect( Qt::LeftToRight,
  14.                                      Qt::AlignCenter,
  15.                                      newSize,
  16.                                      qApp->desktop()->availableGeometry() )
  17.                 );
  18.  
  19. }

Categories: