QT: Center Window In Screen


I recently started working with c++ and it was a need to create a simple gui application. Most people who come from Visual Studio backgrounds know how easy it is to create a GUI application in seconds using visual studio..

Well, I found out, it was equally easy in C++ (The Myth). Well, after I started I hit on a problem. As usual, I wanted to display my window in the center on the screen when starting. In visual studio, all I had to was select the form properties and set the position.

C++ does not have that easy way with QT. I scoured the net to find some examples and I am sharing here the one I thought the best and efficient.

Open your filename.cpp inside QT Creator or your favorite IDE of choice,

Your main CPP file might like look like this at the first point. This code will create the GUI window in the top left corner.

YourClassName::YourClassName(QWidget *parent):QFrame(parent),ui(new Ui::YourClassName)

Now to center the window, Copy paste the below code and try executing it,

YourClassName::YourClassName(QWidget *parent):QFrame(parent),ui(new Ui::YourClassName)
  QRect position = frameGeometry();

You have to import,

#include “QRect”
#include “QDesktopWidget”

If you don’t import QDesktopWidget, you will get a myriad of errors saying improper struct etc.. After the above code is inserted into your constructor, the window will appear in the center of the screen.

Leave your comments if you found a better way or if you run into a wall…

Share this:
Share this page via Email Share this page via Stumble Upon Share this page via Digg this Share this page via Facebook Share this page via Twitter

Warning: Missing argument 1 for cwppos_show_review(), called in /home/thedaz5/public_html/source/wp-content/themes/flat/content-single.php on line 29 and defined in /home/thedaz5/public_html/source/wp-content/plugins/wp-product-review/includes/legacy.php on line 18

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge