QWidget居中顯示(qt窗口坐標原點是在”左上角”的,有圖)
阿新 • • 發佈:2017-12-08
.com 分享 wid 鏈接 central 技術 cti logs param
轉載請說明出處, 並附上原文鏈接http://blog.csdn.net/qq907482638/article/details/72189014.
問題描述
在Qt學習過程中,在讓QDialog居中顯示的時候, 出現了一點問題. 然而百度的都是大同小異. 都不行.不知道為什麽, 難道是我的搜索姿勢不對. 於是自己實現了居中顯示的函數.
須知
- 以下函數只要繼承QWidget都可以使用.
- 例如 QDialog, QPushButton( -v- 一個居中的”引爆按鈕”)
- 關於坐標問題: 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)就行了.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
實現細節
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;
}
http://blog.csdn.net/qq907482638/article/details/72189014
QWidget居中顯示(qt窗口坐標原點是在”左上角”的,有圖)