如何居中QDialog

How to center QDialog?

本文关键字:QDialog 何居中      更新时间:2023-10-16

我正在尝试将我的QDialog居中。

这是我使用的代码:

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

但是我没有在适当的位置进行对话。当我打印对话框的宽度和高度值时,我注意到它们比实际值小得多。为了检查某些东西是否以错误的方式工作,我更改了它的几何形状:

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

我的对话缩小了...

有人可以告诉我发生了什么吗?

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

首先获取您自己的窗口 rect 的副本。

windowRect.moveCenter(screenGeometry.center());

将副本移动到屏幕矩形的中心。

move(windowRect.topLeft());

执行实际移动:将窗口左上角设置为计算出的左上点。无需调整大小。