how to center a Qt mainform on the screen?

David Burson picture David Burson · Aug 6, 2010 · Viewed 9.7k times · Source

I've tried these in my mainform's 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 put the bottom right corner of the form at about the center of the screen, instead of centering the form. Any ideas?

Answer

Kaleb Pederson picture Kaleb Pederson · Aug 6, 2010

I've tried these in my mainform's constructor

That's likely the problem. You probably don't have valid geometry information at this point because the object isn't visible.

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

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

But, after being shown:

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

Thus, you can't yet rely on your frameGeometry() information.

EDIT: With that said, I presume you can easily move it as desired, but for completeness I'm dropping in Patrice's code which doesn't depend on the frame geometry information:

QRect desktopRect = QApplication::desktop()->availableGeometry(this);
QPoint center = desktopRect.center();

move(center.x() - width() * 0.5, center.y() - height() * 0.5);