计算器生成器
在运行时基于Qt Widgets Designer 表单创建用户界面。

我们将使用“计算器表单”示例中创建的表单,以说明同一用户界面既可以在应用程序运行时生成,也可以在应用程序构建时定义。
准备工作
“计算器表单”示例定义了一个用户界面,我们可以直接使用而无需修改。在本示例中,我们使用资源文件来存放上一个示例中创建的calculatorform.ui 文件,但该文件也可以直接存储在磁盘上。
要在运行时生成窗体,我们需要将示例与QtUiTools 模块库进行链接。我们使用的项目文件包含完成此操作所需的所有必要信息:
target_link_libraries(calculatorbuilder PRIVATE
Qt6::UiTools
Qt6::Widgets
)UI 文件从资源中加载:
qt_add_resources(calculatorbuilder "calculatorbuilder"
PREFIX
"/forms"
FILES
"calculatorform.ui"
)对于qmake :
RESOURCES = calculatorbuilder.qrc
SOURCES = main.cpp
QT += widgets uitools所有其他必需的文件均按常规方式声明。
加载计算器表单
我们将需要使用libQtUiTools 库提供的QUiLoader 类,因此首先确保已包含该类的头文件:
#include <QUiLoader>我们创建一个静态辅助函数,该函数用于创建一个顶级控件,并通过QFile 对象从示例资源中加载用户界面:
static QWidget *loadCalculatorForm(QWidget *parent = nullptr)
{
QFile file(u":/forms/calculatorform.ui"_s);
if (!file.open(QFile::ReadOnly))
return nullptr;
QWidget *formWidget = QUiLoader().load(&file, parent);
if (!formWidget)
return nullptr;通过将用户界面包含在示例的资源中,我们确保在运行示例时该界面会存在。QUiLoader::load() 函数会读取文件中包含的用户界面描述,并将表单控件构建为CalculatorForm 的子控件。
在生成的用户界面中,我们关注三个控件:两个旋转框和一个标签。为方便起见,我们从FormBuilder 生成的控件中获取这些控件的指针,并将其记录下来以备后用。findChild() 模板函数允许我们查询控件,从而查找命名的子控件。
auto *inputSpinBox1 = formWidget->findChild<QSpinBox*>(u"inputSpinBox1"_s);
auto *inputSpinBox2 = formWidget->findChild<QSpinBox*>(u"inputSpinBox2"_s);
auto *outputWidget = formWidget->findChild<QLabel*>(u"outputWidget"_s);用于修改表单提供的输出控件的插槽,其定义方式与“计算器表单”示例中的类似,只是我们使用了一个 lambda 表达式来捕获找到的控件:
auto updateResult = [inputSpinBox1, inputSpinBox2, outputWidget]()
{
const int sum = inputSpinBox1->value() + inputSpinBox2->value();
outputWidget->setText(QString::number(sum));
};
QObject::connect(inputSpinBox1, &QSpinBox::valueChanged, formWidget, updateResult);
QObject::connect(inputSpinBox2, &QSpinBox::valueChanged, formWidget, updateResult);表单控件被添加到布局中,并设置了窗口标题:
auto *layout = new QVBoxLayout(&w);
layout->addWidget(formWidget);
w.setWindowTitle(QCoreApplication::translate("CalculatorForm",
"Calculator Builder"));这种方法的优势在于,在应用程序运行时我们可以替换表单,但只要其中的控件被赋予了适当的名称,我们仍然可以对其进行操作。
然而,与使用User Interface Compiler (uic)工具将其转换为C++代码相比,在运行时加载表单会产生额外的运行时开销。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.