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
- A Text Label
- A Text Field
- A Button
- 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