Tuesday, August 05, 2008

Qt - A Simple Example

Enough of the theory; let’s get into the action. Here is a sample window which will take a name and displaying a message. Before we get into the coding part, it is more important to analyze how the window works.

Basically this window can be broken down into 4 components

  1. A Text Label
  2. A Text Field
  3. A Button
  4. A Message Box

Now let’s see how the system works. A user keys in his name, then clicks the button, once the button is clicked a message box appears which reads from the text field and displays a message. Download the source from here.

Primarily an application is created from the QApplication class, and then a complex widget is created and assigned as the main widget of the application and then is displayed after resizing it.

As there are many simple widgets in the application, a complex widget is created from them, and then set to the application. Here the class ComplexBox represents the complex widget. Remember every widget is derived from the QWidget class.

Firstly the components are to be created and then placed on the screen; this is done by using a layout, namely the grid layout. Where the component is placed based on the co-ordinates of the layout. For example the text label is placed at position (1, 1) extending to (1, 2), that is it occupies 2 columns and 1 row starting from (1,1). Similarly all the other components are placed.

Next we have the inter-actions between various components. As we can see, clicking the button leads to display of the message. This is the perfect situation of an action listener; this is implemented in Qt by a signal-slot relationship. The signal and the slot are primarily functions. Here the signal is generated by a pre-defined signal called the clicked() of the button, as a result an action is performed by the call() slot of the ComplexBox object itself. As seen the slot is declared in the header.

That’s it; our first Qt program is over. Run these commands to compile it

qmake –project
qmake
make
./dir-name

3 comments:

Anonymous said...

It was extremely interesting for me to read the post. Thank author for it. I like such topics and everything connected to this matter. I would like to read a bit more on that blog soon.

donkeykong64 said...

The link to the source code seems to be broken. Maybe the file has been removed?

Gautam Muduganti said...

@donkeykong64 - yes the link seems to be broken, I will fix it by the night. I will let you know once I have updated the link.