Implementign User Interface Layouts
Layout Implementation Approaches
Three common methods for implementing form-based user interfaces:
- Absolute positioning of comopnent coordinates and sizes
- Nested QBoxLayout containers
- Grid-based layout using QGridLayout
Grid Layout Implementation
Header file definition for the widget class:
#ifndef FORM_WIDGET_H
#define FORM_WIDGET_H
#include <QWidget>
class FormWidget : public QWidget
{
Q_OBJECT
public:
explicit FormWidget(QWidget* parent = nullptr);
~FormWidget();
};
#endif
Implementation using QGridLayout for form arrangement:
#include "FormWidget.h"
#include <QLabel>
#include <QLineEdit>
#include <QGridLayout>
FormWidget::FormWidget(QWidget* parent)
: QWidget(parent, Qt::WindowCloseButtonHint)
{
QLabel* nameLabel = new QLabel("Name:");
QLabel* emailLabel = new QLabel("Email:");
QLabel* addrLabel = new QLabel("Address:");
QLineEdit* nameInput = new QLineEdit();
QLineEdit* emailInput = new QLineEdit();
QLineEdit* addrInput = new QLineEdit();
QGridLayout* mainLayout = new QGridLayout();
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(emailLabel, 1, 0);
mainLayout->addWidget(addrLabel, 2, 0);
mainLayout->addWidget(nameInput, 0, 1);
mainLayout->addWidget(emailInput, 1, 1);
mainLayout->addWidget(addrInput, 2, 1);
mainLayout->setSpacing(10);
setLayout(mainLayout);
}
FormWidget::~FormWidget() {}
Application entry point:
#include <QApplication>
#include "FormWidget.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
FormWidget widget;
widget.show();
return app.exec();
}
QFormLayout Manager
Form-Based Layout Managemant
QFormLayout provides specialized management for form-style interfaces where labels and input components maintain corresponding relationships.
QFormLayout Usage
Header file remains consistent:
#ifndef FORM_WIDGET_H
#define FORM_WIDGET_H
#include <QWidget>
class FormWidget : public QWidget
{
Q_OBJECT
public:
explicit FormWidget(QWidget* parent = nullptr);
~FormWidget();
};
#endif
Implementation using QFormLayout for streamlined form creation:
#include "FormWidget.h"
#include <QLineEdit>
#include <QFormLayout>
FormWidget::FormWidget(QWidget* parent)
: QWidget(parent, Qt::WindowCloseButtonHint)
{
QLineEdit* nameField = new QLineEdit();
QLineEdit* emailField = new QLineEdit();
QLineEdit* addressField = new QLineEdit();
QFormLayout* formLayout = new QFormLayout();
formLayout->addRow("Name:", nameField);
formLayout->addRow("Email:", emailField);
formLayout->addRow("Address:", addressField);
formLayout->setRowWrapPolicy(QFormLayout::WrapAllRows);
formLayout->setLabelAlignment(Qt::AlignRight);
formLayout->setSpacing(10);
setLayout(formLayout);
}
FormWidget::~FormWidget() {}
Application execution code:
#include <QApplication>
#include "FormWidget.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
FormWidget mainWindow;
mainWindow.show();
return app.exec();
}