topic logo
Qt ⇢ Unit 9

Form Layout

the fourth layout type

Summary

Form layouts are a quick way to make linked two column layouts.

Background

Forms are a common input paradigm. They consist a sequence of labels on the left side and input fields on the right. Qt provides a convenience layout class to quickly create such constructs.

New Classes

  • QFormLayout: A class optimized for two column, “label -> input” layout creation.

The FormLayout Application

This unit’s example application is very simple consisting only of a few lines of code. It demonstrates the fourth notable class in the layout family which is used to create forms. The project structure, header, etc. is the same as before and application window constructor contains all the interesting code.

Note the Underline Below Certain Letters
Note the Underline Below Certain Letters

The Constructor

formlayout.cpp - constructor
FormLayout::FormLayout()
{
    auto layout = new QFormLayout(this);
    layout->addRow("&Speed:", new QLineEdit());
    layout->addRow("&Temperature:", new QLineEdit());
    layout->addRow("&Viscosity:", new QLineEdit());
}

The first line in the listing creates a new form layout and applies it to the application window.

Forms consist of rows, usually containing a label and an input field. The “QFormLayout::addRow(labelText, input)” method creates a new row. It puts a label with the first argument in the first column and the input in the second.

These two widgets share a special relationship: they are “buddy’s”, which is all about keyboard navigation. The “&” character in the listing above specifies a “hotkey” for the label. When the application is running and the user types “[Alt] + [hotkey]“, the form will jump to the input field that is in the same row as the label. With this mechanism even very complex applications can be operated using only the keyboards.

Although used in the listing, the QLineEdit class is not formally introduced in this unit. It’s a simple one-line input class that will be featured in a unit not far away.

Conclusion

This was the last of the layout introduction units. Together they allow the creation of almost any layout variation and even provide a few optimized methods to do so, i.e. manual composition vs grid generation in a loop and specialized forms.

The following units will introduce useful widgets that form the Qt framework widgets module, e.g. various types of inputs, container widgets, menus, and more.