How to center QDialog?

I'm trying to center my QDialog.

Here's a code I used:

QRect screenGeometry = QApplication::desktop()->screenGeometry();
int x = (screenGeometry.width() - this->width()) / 2;
int y = (screenGeometry.height() - this->height()) / 2;
this->move(x, y);

But I didn't get my dialog at an appropriate posistion. When I printed values of a dialog's width and height I noticed that they were much smaller than a real ones. To check if something was working in a wrong way I changed it's geometry:

this->setGeometry(100,100,this->width(),this->height());

And my dialog shrank...

Can someone tell me what's going on?

Upvotes: 2

Views: 275

Answers (1)

jonspaceharper
jonspaceharper

Reputation: 4367

QRect screenGeometry = QApplication::desktop()->screenGeometry();
QRect windowRect = rect();

First get a copy of your own window rect.

windowRect.moveCenter(screenGeometry.center());

Move the copy to the center of the screen's rect.

move(windowRect.topLeft());

Perform the actual move: set your windows top left point to the calculated top left point. No resize is necessary.

Upvotes: 1

Related Questions