C++, QT4

Simple ui using QT4 and C++

Today we will create a simple qt4 window that is centered on screen.

Assuming that you have already installed qt4 libraries.

1. Create a folder in your system and name it for ex. simple_window.
2. Create a file, name it for ex. sw.cpp and paste the following code:

#include <QApplication>
#include <QDesktopWidget>
#include <QWidget>
 
int main(int argc, char *argv[])
{
  //vars
  int w = 400; int h = 200;
  int x, y;
 
  //initialize
  QApplication app(argc, argv);
  QWidget wnd;
  QDesktopWidget *desktop = QApplication::desktop();
 
  //calculate dimensions
  x = (desktop->width() - w) / 2;
  y = (desktop->height() - h) / 2;
 
  //resize and move
  wnd.resize(w, h);
  wnd.move( x, y );
 
  //set title
  wnd.setWindowTitle("Hello, world!");
 
  //show-run
  wnd.show();
  return app.exec();
}

3. Open console and navigate to simple_app folder.
4. Type:

qmake -project

to create your .pro file. Your pro file will look like this:

######################################################################
# Automatically generated by qmake (2.01a) Sat Mar 17 09:11:41 2012
######################################################################
 
TEMPLATE = app
TARGET = 
DEPENDPATH += .
INCLUDEPATH += .
 
# Input
SOURCES += sw.cpp

5. Issue the following command:

qmake

6. Issue the following command:

make

7. Run the application:

./simple_window

8. The result:

simple window