Search code examples
qtqt4qt-designerqmainwindow

How to display a widget inside a main window


I have a project marines with the following files structure:

  • marines.pro

  • FORMS

    • iran.ui
    • marines.h
  • Headers

    • iran.h
    • marines.h
  • Sources

    • iran.cpp
    • main.cpp
    • marines.cpp

I added the widget iran in the project marines.

Here is marines.cpp

#include <QtGui>
#include "marines.h"
#include "iran.h"


marines::marines(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::marines)
{
    ui->setupUi(this);
    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionIran, SIGNAL(triggered()), this, SLOT(ir()));
}

void marines::ir()
{
//slot to display iran ui inside my main window
}

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

and here is my iran.cpp

#include "iran.h"
#include <QtGui>

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

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

How can I display the widget iran I made in Qt Designer?


Solution

  • It all depends on how you want the widget to be displayed.

    1. You could add a layout to your central widget in your MainWindow and add your custom widget to the layout.
    2. If you want your custom widget to be centralWidget of the MainWindow then use setCentralWidget.
    3. If you want the custom widget as a subWindow then add MdiArea to your MainWindow. Then add custom widget to you MdiArea.
    4. If you just want the custom widget to be displayed as a window, then just use widget.show().

    It's better to look at Qt's examples to understand how a MainWindow is used.