本页内容

计算器表单/多重继承

在应用程序中使用通过Qt Widgets Designer 创建的表单。

“多重继承示例”演示了如何在应用程序中使用通过 Qt Widgets Designer 在应用程序中使用,方法是同时继承QWidget 和用户界面类Ui::CalculatorForm 。

要继承calculatorform.ui 文件,并确保qmake 能通过uic 对其进行处理,我们必须在.pro 文件中包含calculatorform.ui ,如下所示:

QT += widgets

HEADERS = calculatorform.h
SOURCES = calculatorform.cpp main.cpp
FORMS = calculatorform.ui

当项目编译时,uic 将生成相应的ui_calculatorform.h 。

CalculatorForm 定义

在CalculatorForm 的定义中,我们引入了之前生成的ui_calculatorform.h 。

#include "ui_calculatorform.h"

如前所述,该类同时继承自QWidget 和Ui::CalculatorForm 。

class CalculatorForm : public QWidget, private Ui::CalculatorForm
{
    Q_OBJECT

public:
    explicit CalculatorForm(QWidget *parent = nullptr);

private slots:
    void on_inputSpinBox1_valueChanged(int value);
    void on_inputSpinBox2_valueChanged(int value);
};

根据uic 要求的自动连接命名约定,定义了两个插槽。这是为了确保QMetaObject 的自动连接功能能够自动连接所有相关的信号和插槽。

CalculatorForm 的实现

在构造函数中,我们调用setupUi() 来加载用户界面文件。请注意,setupUi 是Ui::CalculatorForm 的一个方法。

CalculatorForm::CalculatorForm(QWidget *parent)
    : QWidget(parent)
{
    setupUi(this);
}

我们包含两个槽:on_inputSpinBox1_valueChanged() 和on_inputSpinBox2_valueChanged() 。这两个槽响应两个旋转框共同发出的valueChanged() 信号。每当其中一个旋转框的值发生变化时,我们会将该值与另一个旋转框的当前值相加。

void CalculatorForm::on_inputSpinBox1_valueChanged(int value)
{
    outputWidget->setText(QString::number(value + inputSpinBox2->value()));
}

void CalculatorForm::on_inputSpinBox2_valueChanged(int value)
{
    outputWidget->setText(QString::number(value + inputSpinBox1->value()));
}

main() 函数

main() 函数会实例化QApplication 和CalculatorForm 。通过调用show() 函数来显示calculator 对象。

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    CalculatorForm calculator;
    calculator.show();
    return app.exec();
}

将表单纳入应用程序的方法多种多样。多重继承方法只是其中之一。有关其他可用方法的更多信息,请参阅《在应用程序中使用Qt Widgets Designer UI 文件》。

示例项目 @ code.qt.io

© 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.