PDA

View Full Version : Puzzling class member and its usage in class constructor



Karen
15th June 2015, 18:50
I inherited a piece of code as the following:

In the header file:

namespace Ui
{
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
Ui::MainWindow *ui;
...
}

In cpp file, the class constructor as defined as below:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)

Question is why a pointer to itself in the header file? Is this not just "this" as in C++?

Then in the constructor, ui(new Ui::MainWindow) is used in the constructor. What does it do to the constructor?

jefftee
15th June 2015, 19:25
Question is why a pointer to itself in the header file? Is this not just "this" as in C++?

Then in the constructor, ui(new Ui::MainWindow) is used in the constructor. What does it do to the constructor?
This code is generated by the Qt meta object system.

Look at your ui_MainWindow.h file that is generated by qmake and you'll see this is generated for the form you have created in the designer.

Radek
15th June 2015, 19:31
Nothing puzzling here. MainWindow is not the same as Ui::MainWindow. There is ui_mainwindow.h header somewhere around which contains the definition of Ui::MainWindow. The header should be either included in the header of your snippet, or the ctor includes the MOC file. You will often see this kind of coding in Qt. Please, accept.

ChrisW67
15th June 2015, 21:26
The class Ui::MainWindow is the generated implementation or your Designer form (mainwindow.ui -> uic -> ui_mainwindow.h). An instance of that class is maintained privately by the form class MainWindow (which lives in the global namespace and not the Ui namespace). The Ui::mainWindow instance is created on the heap in the form class constructor initialization list. This is standard C++, nothing sneaky about it.

Karen
16th June 2015, 17:50
Thank you all for replies. Yes, indeed I found the Ui::MainWindow definition in ui_mainwindow.h that's generated by Qt ui compiler. That answered my question.