Пример "Calculator Builder"

The Calculator Builder example shows how to create a user interface from a Qt Designer form at run-time, using the QUiLoader class.

We use the form created in the Calculator Form example to show that the same user interface can be generated when the application is executed or defined when the application is built.

Подготовка

The Calculator Form example defines a user interface that we can use without modification. In this example, we use a resource file to contain the calculatorform.ui file created in the previous example, but it could be stored on disk instead.

To generate a form at run time, we need to link the example against the QtUiTools module library. The project file we use contains all the necessary information to do this:

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

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:

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.

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: