Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt C++ Initialization List Confusion

I'm getting started with Qt (and C++, to a lesser extent), and I wanted to be sure I fully understood the base code before continuing on. I understand that the first element in the initialization list is being used to select a non-default inherited constructor.

What is the purpose of ui(new Ui::TestAppMain), though? It seems to me like it would be an infinite loop, since ui is being set to a new instance of TestAppMain in the constructor, but that's not the case.

namespace Ui {
    class TestAppMain;
}

class TestAppMain : public QMainWindow{
    public:
        explicit TestAppMain(QWidget *parent = 0);

    private:
        Ui::TestAppMain *ui;
};

TestAppMain::TestAppMain(QWidget *parent): QMainWindow(parent), ui(new Ui::TestAppMain){
    ui->setupUi(this);
}
like image 237
Shook Avatar asked Dec 28 '22 14:12

Shook


1 Answers

Ui::TestAppMain is not the same as your TestAppMain class. It's another C++ class that is generated by Qt from the .ui file you've created in Qt Creator. To avoid confusion and naming conflicts, Qt puts all such generated classes in the Ui namespace.

It is a standard Qt practice to include an instance of Ui::MyWidget in your own class MyWidget. In your case, after you instantiate Ui::TestAppMain, you use that object to initialize your main window (represented by your TestAppMain class) according to the layout you've specified in TestAppMain.ui. That is done by calling ui->setupUi(this).

like image 182
TotoroTotoro Avatar answered Jan 14 '23 11:01

TotoroTotoro