须知
- 以下函数只要继承QWidget都可以使用.
- 例如 QDialog, QPushButton( -v- 一个居中的”引爆按钮”)
- 关于坐标问题: qt窗口坐标原点是在”左上角”的.
如图, (x2, y2)是我窗口的分辨率的一半无论目前我的窗口在什么位置,我只要把窗口原点设置为(x1, y1)就行了.所以目前我要获得(x1, y1)的值, 那就很简单啦.通过//app就是当前要居中的窗口appWindowWidth = app->geometry()->width();appWindowHeight = app->geometry()->height();x2 = 屏幕宽度 / 2y2 = 屏幕高度 / 2最后:x1 = x2 - appWindowWidth / 2y1 = 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;
}
参考:
https://www.yuque.com/docs/share/0b789e2c-6aa9-4c2b-85dd-93f28c2216f0