- An advantage of the namespace is that it prevents naming clashes. All the automatically generated names from QtDesigner stay in their own namespace.
- An advantage of making the Ui class a member, instead of using multiple inheritance, is that the Ui class only needs to be forward-declarded in the header. In your code, you have a
#include "ui_mainwindow.h"
, and that in turn drags in a lot of includes from QtWidgets like<QLabel>
,<QPushButton>
etc. This decreases compilation speed significantly, as everyone who includesmainwindow.h
now also includes those QtWidgets includes. When using the Ui class as a member and forward-declaring it, all these includes only need to be compiled when compilingmainwindow.cpp
, but not when includingmainwindow.h
from somewhere else.
Inheriting a MainWindow class from QMainWindow and Ui_MainWindow
-
01-06-2022 - |
Question
I am learning Qt, Qt 5. When I start Qt Creator and create a project with ALL the default settings, I get these 2 files generated, (I am excluding main.cpp and the .pro file)
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
Now, I prefer to do it this way,
my_mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "ui_mainwindow.h"
class MainWindow : public QMainWindow, private Ui_MainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
};
#endif // MAINWINDOW_H
my_mainwindow.cpp
#include "my_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
setupUi(this);
}
MainWindow::~MainWindow()
{
}
Here are the main differences between my code and Qt Creator's code:
- No
namespace Ui
in my code. (Could anyone explain me the use of this namespace here ?) - I inherit the
MainWindow
class from bothQMainWindow
andUi_MainWindow
whereas the Qt Creator's code inherits it only from theQMainWindow
class.
My question is, is there ANY disadvantage of using my approach or is there any advantage of using the Qt Creator's approach ? Please give a detailed answer.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow