Note that we do not need to include a header file to describe the user interface. We only define two public slots, using the auto-connection naming convention required by uic, and declare private variables that we will use to access widgets provided by the form after they are constructed.
CalculatorForm Class Implementation
We will need to use the QUiLoader class that is provided by the libQtUiTools library, so we first ensure that we include the header file for the module:
#include <QtUiTools>
The constructor uses a form loader object to construct the user interface that we retrieve, via a QFile object, from the example's resources:
CalculatorForm::CalculatorForm(QWidget *parent)
: QWidget(parent)
{
QUiLoader loader;
QFile file(":/forms/calculatorform.ui");
file.open(QFile::ReadOnly);
QWidget *formWidget = loader.load(&file, this);
file.close();
By including the user interface in the example's resources, we ensure that it will be present when the example is run. The loader.load() function takes the user interface description contained in the file and constructs the form widget as a child widget of the CalculatorForm.
We are interested in three widgets in the generated user interface: two spin boxes and a label. For convenience, we retrieve pointers to these widgets from the widget that was constructed by the FormBuilder, and we record them for later use. The qFindChild() template function allows us to query widgets in order to find named child widgets.
ui_inputSpinBox1 = qFindChild<QSpinBox*>(this, "inputSpinBox1");
ui_inputSpinBox2 = qFindChild<QSpinBox*>(this, "inputSpinBox2");
ui_outputWidget = qFindChild<QLabel*>(this, "outputWidget");
The widgets created by the form loader need to be connected to the specially-named slots in the CalculatorForm object. We use Qt's meta-object system to enable these connections:
QMetaObject::connectSlotsByName(this);
The form widget is added to a layout, and the window title is set:
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(formWidget);
setLayout(layout);
setWindowTitle(tr("Calculator Builder"));
}
The two slots that modify widgets provided by the form are defined in a similar way to those in the Calculator Form example, except that we read the values from the spin boxes and write the result to the output widget via the pointers we recorded in the constructor:
void CalculatorForm::on_inputSpinBox1_valueChanged(int value)
{
ui_outputWidget->setText(QString::number(value + ui_inputSpinBox2->value()));
}
void CalculatorForm::on_inputSpinBox2_valueChanged(int value)
{
ui_outputWidget->setText(QString::number(value + ui_inputSpinBox1->value()));
}
The advantage of this approach is that we can replace the form when the application is run, but we can still manipulate the widgets it contains as long as they are given appropriate names.