QT 让窗口(或控件)居中

时间:2021-01-30 11:06:28

代码如下:

  1. XXX::XXX(QWidget *parent /* = 0 */)
  2. {
  3. ..................
  4. //注意,resize一定要放在这段代码的前面
  5. resize(300, 300);
  6. int cx, cy;
  7. //当parent为空时,窗口就显示在桌面*
  8. if( NULL == parent )
  9. {
  10. cx = (QApplication::desktop()->width() - width()) / 2;
  11. cy = (QApplication::desktop()->height() - height()) / 2;
  12. }
  13. //否则,控件就显示在父部件*
  14. else
  15. {
  16. cx = ( parent->width() - width() ) / 2;
  17. cy = ( parent->height() - height() ) / 2;
  18. }
  19. move(cx, cy);
  20. ....................
  21. }

这段代码太常用了,就发上来和大家共享一下吧,呵呵。

http://blog.csdn.net/small_qch/article/details/6973956