7

我在我的主窗体的构造函数中尝试了这些:

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

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

但两者都将表单的右下角放在屏幕的中心,而不是使表单居中。有任何想法吗?

4

7 回答 7

13

我已经在我的主窗体的构造函数中尝试过这些

这很可能是问题所在。此时您可能没有有效的几何信息,因为该对象不可见。

当对象第一次被构造时,它基本上定位在(0,0)它的预期位置(width,height),如下所示:

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

但是,显示后:

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

因此,您还不能依赖您的frameGeometry()信息。

编辑:话虽如此,我认为您可以根据需要轻松移动它,但为了完整起见,我将放入不依赖于框架几何信息的Patrice 代码:

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

move(center.x() - width() * 0.5, center.y() - height() * 0.5);
于 2010-08-06T15:28:45.217 回答
4

move 函数(参见QWidget文档)将一个 QPoint 或两个 int 作为参数。这对应于 Widget 左上角的坐标(相对于其父级;此处为 OS 桌面)。尝试:

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

move(center.x()-width*0.5, center.y()-height*0.5);
于 2010-08-06T15:25:26.300 回答
4

availableGeometry()已弃用。

move(pos() + (QGuiApplication::primaryScreen()->geometry().center() - geometry().center()));
于 2018-09-04T14:08:18.320 回答
2
#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

于 2017-10-20T02:16:47.767 回答
1

move(QGuiApplication::primaryScreen()->geometry().center() - rect().center());

于 2021-06-18T13:14:51.500 回答
0

PyQT Python 版本

# 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);   
于 2018-08-21T15:08:32.853 回答
-1

另一种解决方案,假设有问题的窗口是 800×800:

QRect rec = QApplication::desktop()->availableGeometry();
move(QPoint((rec.width()-800)/2, (rec.height()-800)/2));
于 2016-09-19T21:25:36.523 回答