Why does Qt Creator generate projects that will not compile?


I'm not new to C++ or programming in general, but this is my first attempt at using Qt. When I create a new project it makes this mainwindow.cpp file:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"

    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)

        delete ui;

Without touching that file and just making some changes in the ui file with the designer, then attempting to build the project for a preview, I get two "invalid use of incomplete type" issues for the lines ui(new Ui::MainWindow) and ui->setupUi(this);.

From what I understand, the problem is that it's trying to reference MainWindow before the class is instantiated. But Creator generated that code itself. Is that normal for a new Qt project? Did I skip a step somewhere? More importantly, what is the best way to fix that problem?

In addition to the great explanation by Kuba Ober:

I just want to add that the name of the class generated by the User Interface Compiler in the header ui_*.h (in your case it is ui_mainwindow.h) can be controlled from the designer by changing the objectName property of the main window:

Most likely, You have changed that into something else. This will cause inconsistency between your code (written in the files mainwindow.h, mainwindow.cpp) and the auto-generated code from the UIC (in the file ui_mainwindow.h). Where the former continue to refer to the class as MainWindow while the latter had that name changed.

And since Ui::MainWindow is forward declared in mainwindow.h, it becomes an incomplete type (and hence the error you get). because its definition (generated in ui_mainwindow.h) is done to different name.