QWidget居中顯示

家人是最好的禮物發表於2017-05-15

轉載請說明出處, 並附上原文連結http://blog.csdn.net/qq907482638/article/details/72189014.

問題描述

在Qt學習過程中,在讓QDialog居中顯示的時候, 出現了一點問題. 然而百度的都是大同小異. 都不行.不知道為什麼, 難道是我的搜尋姿勢不對. 於是自己實現了居中顯示的函式.

須知

  1. 以下函式只要繼承QWidget都可以使用.
  2. 例如 QDialog, QPushButton( -v- 一個居中的”引爆按鈕”)
  3. 關於座標問題: qt視窗座標原點是在”左上角”的.

這裡寫圖片描述

    如圖, (x2, y2)是我視窗的解析度的一半
        無論目前我的視窗在什麼位置,我只要把視窗原點設定為(x1, y1)就行了.
        所以目前我要獲得(x1, y1)的值, 那就很簡單啦.
        通過
         //app就是當前要居中的視窗
        appWindowWidth = app->geometry()->width();
        appWindowHeight = app->geometry()->height();
        x2 = 螢幕寬度 / 2
        y2 = 螢幕高度 / 2
        最後:
        x1 = x2 - appWindowWidth / 2
        y1 = y2 -appWindowHeight / 2
        然後把視窗中心設定為(x1, y1)就行了.

實現細節

void LoginDialog::setCentralDisplay()
{
    QDesktopWidget *screenResolution = QApplication::desktop();
    int appWindowWidth = this->geometry().width();
    int appWindowHeight = this->geometry().height();

    int center_y = screenResolution->height()/2 - appWindowHeight/2;
    int center_x = screenResolution->width()/2 - appWindowWidth/2;
    //此處的Width,Height不要被修改了(例如除以2了)
   //不然看起來不是居中的
    setGeometry(center_x, center_y, 
                appWindowWidth,appWindowHeight);

    //以下用於除錯
    qDebug()<<"origin_width"<<screenResolution->width();
    qDebug()<<"origin_height"<<screenResolution->height();
    qDebug()<<"window_width"<<appWindowWidth;
    qDebug()<<"window_height"<<appWindowHeight;
    qDebug()<<"center"<<center_x;
    qDebug()<<"center"<<center_y;


}

相關文章