9.4.  Form Layout

[ fromfile: formlayout.xml id: formlayout ]

Figure 9.10.  QFormLayout Example

QFormLayout Example

Example 9.2. src/layouts/form/inputform.h

#ifndef INPUTFORM_H
#define INPUTFORM_H

#include <QDialog>
class QLineEdit;
class QDateEdit;
class QPushButton;
class QDialogButtonBox;

class InputForm : public QDialog {
    Q_OBJECT
public:
    explicit InputForm(QWidget* parent = 0);
    void updateUi();
protected slots:
    void accept();
    void chooseColor();
private:
    QColor m_color;
    QLineEdit* m_name;
    QDateEdit* m_birthday;
    QPushButton* m_colorButton;
    QDialogButtonBox* m_buttons;
};

#endif // INPUTFORM_H

Example 9.3. src/layouts/form/inputform.cpp

[ . . . . ]

    m_name = new QLineEdit;
    m_birthday = new QDateEdit;
    m_birthday->setDisplayFormat("dd/MM/yyyy");
    m_colorButton = new QPushButton(tr("Choose"));
    m_colorButton->setAutoFillBackground(true);

    m_buttons = new QDialogButtonBox(QDialogButtonBox::Ok |
                                     QDialogButtonBox::Cancel);

    QVBoxLayout* vbox = new QVBoxLayout;
    QFormLayout* layout = new QFormLayout;

    layout->addRow(tr("Name"), m_name);     1
    layout->addRow(tr("Birthdate"), m_birthday);
    layout->addRow(tr("Favorite Color"), m_colorButton);

    vbox->addLayout(layout);                2
    vbox->addWidget(m_buttons);

    Q_ASSERT(vbox->parent() == 0);
    Q_ASSERT(m_birthday->parent() == 0);
    setLayout(vbox);                        3
    Q_ASSERT(vbox->parent() == this);
    Q_ASSERT(m_birthday->parent() == this);
    

1

Create/add a QLabel and the input widget in one line.

2

This is how we nest one layout in another.

3

Reparents previously laid-out widgets.