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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章