Time for action – Adding a layout to the form

Select the MainWindow top-level item in the object tree and click on  , the Lay Out Vertically icon in the upper toolbar. The button, labels, and the empty widget will be automatically resized to take all the available space of the form in the central area:

If the items were arranged in a different order, you can drag and drop them to change the order.

Run the application and check that the window's contents are automatically positioned and resized to use all the available space when the window is resized. Unfortunately, the labels take more vertical space than they really require, resulting in an empty space in the application window. We will fix this issue later in this chapter when we learn about size policies.

You can test the layouts of your form without building and running the whole application. Open the Tools menu, go to the Form Editor submenu, and choose the Preview entry. You will see a new window open that looks exactly like the form we just designed. You can resize the window and interact with the objects inside to monitor the behavior of the layouts and widgets. What really happened here is that Qt Creator built a real window for us based on the description that we provided in all the areas of the design mode. Without any compilation, in a blink of an eye, we received a fully working window with all the layouts working and all the properties adjusted to our liking. This is a very important tool, so ensure that you use it often to verify that your layouts are controlling all the widgets as you intended them to—it is much faster than compiling and running the whole application just to check whether the widgets stretch or squeeze properly. You can also resize the form in the central area of the form editor by dragging its bottom-right corner, and if the layouts are set up correctly, the contents should be resized and repositioned.

Now that you can create and display a form, two important operations need to be implemented. First, you need to receive notifications when the user interacts with your form (for example, presses a button) to perform some actions in the code. Second, you need to change the properties of the form's contents programmatically, and fill it with real data (for example, set player names from the code).