LinuxQuestions.org
Support LQ: Use code LQ3 and save $3 on Domain Registration
Go Back   LinuxQuestions.org > Blogs > rainbowsally
User Name
Password

Notices

Rate this Entry

QT4 GUI Programming: Center Window

Posted 05-28-2012 at 12:50 AM by rainbowsally

Today's Features:
  • Center a non-dialog window in qt4.

If you have mc2, 'mc2 -fetch qt4' for the Makefile, otherwise, do whatever you do to get this rolling.

Here are the files for this demo/test.

file: src/main.cpp
Code:
// generic C++ source template created by new.main

#include <stdio.h>  // printf(), FILE*, etc.
#include <malloc.h> // malloc(), free()
#include <string.h> // strcpy(), memcpy(), etc.
#include <stdlib.h> // exit()

#include <QApplication>
#include <QMainWindow>

#include "qt-utils.h"

void dbg(){}

int main(int argc, char** argv)
{
  dbg();
  QApplication* app;
  app = new QApplication(argc, argv);
  // create a main window, notorious for showing in odd places
  QMainWindow* mw = new QMainWindow();
  mw->show();

#if 1  // center it on the screen
  lqCenterWindow(app, mw);
#endif
  
  app->exec();
  
  return 0;
}
file: src/qt-utils.cpp
Code:
#include "qt-utils.h"


// Center any kind of window in the screen accounting for 
// space used by junk at the top, bottom and sides that
// encroaches on usable space. Well.. not that last part.
// TODO: determine usable area and offset as appropriate.
// Window must be show()-ed before repositioning.

void lqCenterWindow(QApplication* app, QWidget* window)
{
  // Unreliable if window isn't shown yet
  if(!window->isVisible())
    return;
  
  int dtx,dty,dtw,dth;
  int winx,winy,winw,winh;
  int x, y;
  
  QDesktopWidget* dt = app->desktop();
  
  // this may not be working. -rs
  dt->availableGeometry().getRect(&dtx,&dty,&dtw,&dth);
  
  window->geometry().getRect(&winx,&winy,&winw,&winh);
  
  x = dtx + dtw/2 - winw/2; // x1 should not always be 0
  y = dty + dth/2 - winh/2; // y1 ""
  
  window->setGeometry(x, y, winw, winh);
}
file: src/qt-utils.h
Code:
// qt-utils.h

#ifndef qt_utils_h
#define qt_utils_h

#include <QApplication>
#include <QRect>
#include <QDesktopWidget>
#include <QMainWindow>

void lqCenterWindow(QApplication* app, QWidget* window);

#endif // qt_utils_h
You can compare with and without the lqCenterWindow() function by changing the '#if' parameter in main.cpp from 1 to 0.

The Computer Mad Science Team

:-)
Posted in Uncategorized
Views 870 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 09:12 PM.

Main Menu
Advertisement

My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration