Qt程序在多屏下居中显示问题

最近碰到个问题,发布的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();
}

作者:fairys husband
来源:CSDN
原文:https://blog.csdn.net/hdaioutgjht/article/details/85310824
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值