`
tcspecial
  • 浏览: 897732 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

QT窗口居中显示

    博客分类:
  • QT
阅读更多

    看到网上很多文章,窗口居中,无非都是move至窗口的中心目标; 有两种方式, 一种在构造函数中直接计算中心坐标; 另一种是在窗口show后再move至相应坐标.

  

    1. 在构造函数中添加

 /** 
   *构建函数中move至中心坐标时, 必须应用setFixedSize(500,500); 否则达不到期望居中显示的目标 
   */ 
Dialog:Dialog(QObject *parent=0):QDialog(parent) { 
	... 
	this->setFixedSize(500,500); //这句必须添加 
	this->setWindowTitle(tr("StyleSheet")); 
	
	QDesktopWidget *desk=QApplication::desktop(); 
	int wd=desk->width(); 
	int ht=desk->height(); 
	this->move((wd-width())/2,(ht-height())/2); 
} 

 

  2. main函数中添加

 

  

/** 
   *方式一: 先显示后移动会产生窗口闪烁,有点不太好
   */ 
int main(int argc,char **argv) { 
   QApplication app(argc,argv); 
   Dialog dialog; 
   dialog.show(); 
  
   QDesktopWidget *desk=QApplication::desktop(); 
   int wd=desk->width(); 
   int ht=desk->height(); 
   dialog.move((wd-dialog.width())/2,(ht-dialog.height())/2); 
   
   return app.exec();
} 

 

 

/**
 *方式二: 在移动和显示窗口前重新设置窗口的大小,这样就能达到期望的效果且不会闪烁
 */
int main(int argc,char **argv)
{
    QApplication app(argc,argv);

    Dialog dialog;
    dialog.resize(500,500); //重新设置大小 

   QDesktopWidget *desk=QApplication::desktop();
    int wd=desk->width();
    int ht=desk->height();
    dialog.move((wd-dialog.width())/2,(ht-dialog.height())/2);
	
   dialog.show();
}

  

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics