How to center the main Qt shape on the screen?

I tried this in my mainform constructor:

QRect desktopRect = QApplication::desktop()->availableGeometry(this); move(desktopRect.center() - frameGeometry().center()); QRect desktopRect = QApplication::desktop()->availableGeometry(this); move(desktopRect.center() - rect().center()); 

but both set the bottom right corner of the shape around the center of the screen, rather than centering the shape. Any ideas?

+7
qt qt4
source share
6 answers

I tried this in my mainform constructor

This is probably the problem. You may not have valid geometry information at this time because the object is not visible.

When an object is first created, it is essentially positioned at (0,0) with the expected (width,height) , as such:

 frame geometry at construction: QRect(0,0 639x479) 

But after the show:

 frame geometry rect: QRect(476,337 968x507) 

Thus, you cannot yet rely on frameGeometry() .

EDIT : With that said, I suppose you can easily move it as you wish, but for completeness I will add a Patrice code that does not depend on information about the frame geometry:

 QRect desktopRect = QApplication::desktop()->availableGeometry(this); QPoint center = desktopRect.center(); move(center.x() - width() * 0.5, center.y() - height() * 0.5); 
+10
source share

The move function (see QWidget doc) accepts one QPoint parameter or two ints as a parameter. This corresponds to the coordinates of the upper left corner of your widget (relative to its parent, here OS Desktop). Try:

 QRect desktopRect = QApplication::desktop()->availableGeometry(this); QPoint center = desktopRect.center(); move(center.x()-width*0.5, center.y()-height*0.5); 
+4
source share
 #include <QStyle> #include <QDesktopWidget> window->setGeometry( QStyle::alignedRect( Qt::LeftToRight, Qt::AlignCenter, window->size(), qApp->desktop()->availableGeometry() ) ); 

https://wiki.qt.io/How_to_Center_a_Window_on_the_Screen

+1
source share

availableGeometry() deprecated.

 move(pos() + (QGuiApplication::primaryScreen()->geometry().center() - geometry().center())); 
+1
source share

PyQT Python Version

 # Center Window desktopRect = QApplication.desktop().availableGeometry(self.window) center = desktopRect.center(); self.window.move(center.x()-self.window.width() * 0.5, center.y()-self.window.height() * 0.5); 
0
source share

Another solution, assuming this window is 800 × 800:

 QRect rec = QApplication::desktop()->availableGeometry(); move(QPoint((rec.width()-800)/2, (rec.height()-800)/2)); 
-one
source share

All Articles