Usage of the QFormLayout

Hi there. Introducing myself, my name is Friedemann Kleint, and I am one of the trolls hacking away at Qt Designer at the Berlin Office.

Today, I would like to draw your attention to the QFormLayout class. This is a special layout class suited to the common descriptive label - control arrangement found in many dialogs. It thas been developed in cooperation between Brisbane, Oslo and Berlin.

A typical form layout looks like this:

QFormLayout example 1

QFormLayout example 2

Note how the layout takes care of the label alignment according to the platform style. By the way, did you know that you can open several previews in different styles in Designer to compare them?

At first sight, QFormLayout looks like an ordinary grid. However, the layout also has policies for wrapping rows when it shrinks. For example, when setting the property rowWrapPolicy to WrapLongRows, we might get:

QFormLayout’s wrapping policy in effect

Let's first have a look at the code. You might have created a such dialogs using QGridLayout, previously. This required some housekeeping of the current row. This is no longer necessary with QFormLayout using the addRow() convencience function. You don't have to explicitly create the label, either:

QFormLayout *formLayout = new QFormLayout;
formLayout->addRow("Name", new QLineEdit);

For completeness, there is a setWidget() function which allows you to address single cells. It takes a row parameter and an ItemRole enumeration, which can be one of QFormLayout::LabelRole or QFormLayout::FieldRole.

In Qt Designer, you can create such arrangements as would in the case of a QGridLayout; you place the controls on a form and choose "Lay Out in a Form Layout".

Hint: If you have existing .ui files containing such 2-column grid layouts and want to migrate them to the form layout, it might be sufficient to just replace the layout element by something like (after making a backup copy, of course ;-) ).

It is also possible to create arrangements with controls that span the 2 columns. This let's you add controls with long labels (for example QComboBox) or QGroupBox elements. It can also be used to partition the form layout into sections by using spanning QLabel elements:

A form layout arrangement with spanning labels

In code, you would use the addRow() overload that takes just one QWidget* parameter.

In the upcoming 4.5 release, this functionality will also be available in Designer. Lonesone widgets on a QFormLayout get an active left/right resize handle that let's you change the span:

Changing the span of a QFormLayout element in Designer

The per-cell API of the QFormLayout uses the SpanningRole enumeration value of ItemRole to handle these rows.

Summarizing, the QFormLayout should be used whereever the typical descriptive label - control arrangement occurs. The dialog will then look correctly on a all platforms.

Blog Topics: