This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Using a form created with Qt Designer in an application.
The Calculator Form Example shows how to use a form created with Qt Designer in an application by using the user interface information from a
The example presents two spin boxes that are used to input integer values and a label that shows their sum. Whenever either of the spin boxes are updated, the signal-slot connections between the widgets and the form ensure that the label is also updated.
The user interface for this example is designed completely using Qt Designer. The result is a UI file describing the form, the widgets used, any signal-slot connections between them, and other standard user interface properties.
To ensure that the example can use this file, we enable the
CMAKE_AUTOUIC feature and list the UI file in the source files:
<Code snippet "calculatorform/CMakeLists.txt:0" not found> <Code snippet "calculatorform/CMakeLists.txt:1" not found>
qmake, we need to include a
FORMS declaration in the example’s project file:
<Code snippet "calculatorform/calculatorform.pro:1" not found>
When the project is built,
uic will create a header file that lets us construct the form.
CalculatorForm Class Definition#
CalculatorForm class uses the user interface described in the
calculatorform.ui file. To access the form and its contents, we need to include the
ui_calculatorform.h header file created by
uic during the build process:
from ui_calculatorform import *
We define the
CalculatorForm class by subclassing
QWidget because the form itself is based on
class CalculatorForm(QWidget): Q_OBJECT # public CalculatorForm = explicit(QWidget parent = None) # private slots def updateResult(): # private Ui.CalculatorForm ui
Apart from the constructor, the class contains a private slot
updateResult() that performs the calculation and updates the output widget accordingly. The private
ui member variable refers to the form, and is used to access the contents of the user interface.
CalculatorForm Class Implementation#
The constructor simply calls the base class’s constructor, sets up the form’s user interface and connects the signals
valueChanged() to the slot
def __init__(self, parent): super().__init__(parent) ui.setupUi(self) ui.inputSpinBox1.valueChanged.connect(self.updateResult) ui.inputSpinBox2.valueChanged.connect(self.updateResult)
The user interface is set up with the
setupUI() function. We pass
this as the argument to this function to use the
CalculatorForm widget itself as the container for the user interface.
updateResult() adds the values and sets the result on the output widget:
def updateResult(self): sum = ui.inputSpinBox1.value() + ui.inputSpinBox2.value() ui.outputWidget.setText(QString.number(sum))
It is called whenever the value of one of the spin boxes changes.