QT4 GUI Programming: Center Window
Posted 05-28-2012 at 12:50 AM by rainbowsally
Today's Features:
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
file: src/qt-utils.cpp
file: src/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
:-)
- 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; }
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); }
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
The Computer Mad Science Team
:-)
Total Comments 0