Search code examples
c++qtuser-interfaceownership-semantics

What is the relationship between ui and this in Qt?


If you create a Qt widget application with class name MainWindow, Qt Creator will give you this template header:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

and this template source:

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

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

What is ui? What is its relationship to this?


Solution

  • The qt program uic compiles the .ui file to a .h file. It makes a class that holds pointers to all the widgets defined in the form, and a member function setupUi which constructs all those widgets, setting the properties specified in the form, with the top-level widget being a direct child of the passed in widget (your MainWindow instance in this case). It doesn't automatically show any window, other code calls the show member of your main window.

    If you create another Ui::MainWindow and call it's setupUi, you will populate another widget with all the descendant widgets described in the form.