最近碰到个问题,发布的qt程序在多屏幕机器上显示不全的问题,分析后发现是因为使用了程序居中显示的代码,下面为原始代码:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWidget w;
w.move((a.desktop()->width()-w.width())/2,((a.desktop()->height()-w.height())/2));
w.show();
return a.exec();
}
原理很简单,是用像素大小来计算,在单屏幕上也并没有什么问题,但是在多屏下就有问题了,因为多屏下的像素是所有屏幕加起来,所以用上面的方法,程序界面位置是不可预料的。看下帮助文档内容:
However, for desktops with multiple screens, the size of the desktop is the union of all the screen sizes, so width() and height() should not be used for computing the size of a widget to be placed on one of the screens.
所以修改后代码为:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWidget w;
int currentScreen = a.desktop()->screenNumber(&w);//程序所在的屏幕编号
QRect rect = a.desktop()->screenGeometry(currentScreen);//程序所在屏幕尺寸
w.move((rect.width() - w.width()) / 2, (rect.height() - w.height()) / 2);//移动到所在屏幕中间
w.show();
return a.exec();
}