Go Job Hunting at the LQ Job Marketplace
Go Back > Blogs > rainbowsally
User Name


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
// 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)
  QApplication* app;
  app = new QApplication(argc, argv);
  // create a main window, notorious for showing in odd places
  QMainWindow* mw = new QMainWindow();

#if 1  // center it on the screen
  lqCenterWindow(app, mw);
  return 0;
file: src/qt-utils.cpp
#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
  int dtx,dty,dtw,dth;
  int winx,winy,winw,winh;
  int x, y;
  QDesktopWidget* dt = app->desktop();
  // this may not be working. -rs
  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
// 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 816 Comments 0
« Prev     Main     Next »
Total Comments 0




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

Main Menu

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