在 QT 中创建带有表单的控件时的递归构造函数调用

Recursive Constructor Invocation when creating a Widget with form in QT?

本文关键字:控件 递归 函数调用 表单 QT 创建      更新时间:2023-10-16

我试图理解为什么在使用表单创建QWidget时自动生成QT。

这是QT生成的代码:

**********************************************************************
*  widget.h
**********************************************************************
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();
private:
    Ui::Widget *ui;
};
#endif // WIDGET_H
#endif // WIDGET_H
**********************************************************************
*  widget.cpp
**********************************************************************
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);
}
Widget::~Widget()
{
    delete ui;
}
**********************************************************************
*  main.cpp
**********************************************************************
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

我的问题是构造函数中的这条语句:

ui(new ui::Widget)

这是在调用类 Widget 的构造函数时创建一个新的 Widget。这就像递归不是吗?为什么不坏?

它不是递归的,它是ui_Widget.h类的实例,因为您一次
只需要GUI的一个实例这种方法的优点是用户界面对象可以向前声明,这意味着我们不必在标头中包含生成的 ui_Widget.h 文件。然后,可以更改表单,而无需重新编译依赖源文件。如果类受到二进制兼容性限制,这一点尤其重要,因为如您所见,"#include"ui_widget.h"在 cpp a 内不在头文件中

NO。由于命名空间,有两个具有相同名称的不同类:

ui::小部件

控件

Ui::Widget 是表单对象的类。