如何将Qt主窗体居中显示在屏幕上?

7
我已经在主窗体的构造函数中尝试了以下内容:
QRect desktopRect = QApplication::desktop()->availableGeometry(this);
move(desktopRect.center() - frameGeometry().center());

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

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

7个回答

15

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

那很可能是问题所在。因为对象还不可见,所以你可能没有有效的几何信息。

当对象首次构造时,它基本上被定位在(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);

如果我在居中的代码之前调用this->resize(width_I_want, height_I_want),我发现它可以正常工作。谢谢! - David Burson
那很有趣。这会如何改变框架几何结构? - Kaleb Pederson

4

availableGeometry()已被弃用。

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

4

移动函数(参见QWidget文档)需要一个QPoint或两个int作为参数。这对应于您的小部件左上角的坐标(相对于其父级;在此处为操作系统桌面)。 尝试:

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

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

2

1

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


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);   

-1

另一种解决方案,假设所涉及的窗口大小为800×800:

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

我不喜欢假设窗口大小,特别是在高DPI显示器和移动设备不断变化的时代。 - Jonathan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接