问题描述:
一般来说,X86系统下,Qt程序启动时都会自动在屏幕中间显示的。只不过凡事都有例外,偶尔你不知道设置了什么,程序窗口就偏离了中央位置。这里用到了QDesktopWidget这个管理桌面的类。(不过QDesktopWidget官方已经不建议使用了,而是使用QScreen代替)
解决办法:
让程序窗口显示在屏幕中央,需要让窗口移动。所谓窗口移动,实际上是将窗口的左上角的点移动到对应的坐标点,它的位置就是这个坐标。
代码:
MainWindow w;
//移动窗体到屏幕中央
QRect rect = w.frameGeometry();
QDesktopWidget desktop;
QPoint centerPoint = desktop.availableGeometry().center();
rect.moveCenter(centerPoint);
w.move(rect.topLeft());
w.show();
替换为QScreen:
//移动窗体到屏幕中央
QRect rect = w.frameGeometry();
// QDesktopWidget desktop;
QScreen* screen = QGuiApplication::primaryScreen();
QPoint centerPoint = screen->availableGeometry().center();
rect.moveCenter(centerPoint);
w.move(rect.topLeft());
w.show();
如果有多个屏幕,可以使用QGuiApplication::screens()[0]来代替。具体可以查看screens()用法。