计算器表单/多重继承
在应用程序中使用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
定义中,我们包含了之前生成的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 的自动连接功能能够自动连接所有相关信号和插槽。
计算器窗体的实现
在构造函数中,我们调用setupUi()
来加载用户界面文件。请注意,setupUi 是Ui::CalculatorForm
的一个方法。
我们包含两个插槽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(); }
在应用程序中包含表单有多种方法。多重继承方法只是其中之一。有关其他可用方法的更多信息,请参阅在应用程序中使用设计器 UI 文件。
© 2025 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.