QWidget居中显示(qt窗口坐标原点是在”左上角”的,有图)


转载请说明出处, 并附上原文链接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)就行了.
  • 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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM