Evgenii Legotckoi
Evgenii LegotckoiApril 25, 2017, 10:23 p.m.

Qt/C++ - Tutorial 063. Adding windows inside the main application window using QMdiArea

Many applications, like a photoshop, can open projects (images, texts, etc.) inside windows that open inside the main application window. Qt provides a similar function as QMdiArea . In an object of this class, you can place class objects inherited from the QWidget class, and accordingly the QWidget class. These objects will display as windows, only they will be located inside QMdiArea .

Let's see an example with a window inside the window.


Project structure

The following files are included in the project:

  • MdiWindow.pro - project profile, created by default;
  • main.cpp - the startup file of the program with the main function, created by default;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - the source code file for the main application window;
  • mainwindow.ui - form of the main application window;
  • icons.qrc - resource file, contains one icon.

Files MdiWindow.pro and main.cpp will not be considered, since they are created by default. The file icons.qrc contains one icon, which is visible on the toolbar of the main application window. This button is responsible for creating an additional application window and is added through the graphic designer. This Action is only needed to emit a signal to add new windows to QMdiArea .

Now let's move on to the essence of the project.

mainwindow.h

Header file of the main application window. Contains the declaration of the pointer to the QMdiArea object, as well as the declaration of the slot for adding new windows, which was created through the graphic designer.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMdiArea>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_actionAddWindow_triggered();

private:
    Ui::MainWindow *ui;
    QMdiArea * mdiArea;  // Area in which windows will be added
};

#endif // MAINWINDOW_H

mainwindow.cpp

The QMdiArea object is installed as the central widget for the main application window. Also, configure the scrollbars so that they appear only when necessary. In the add window add a QWidget object with an inscription. There is one point. If QWidget does not contain any content, it will open with a minimum size, even if you size it. And only when you try to move the window, this widget will take the size displayed.

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

#include <QGridLayout>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mdiArea = new QMdiArea(this);  // init QMdiArea
    // configure scrollbars
    mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    // Set Mdi Area as the central widget
    setCentralWidget(mdiArea);
}

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

void MainWindow::on_actionAddWindow_triggered()
{
    // Create a widget that will be a window
    QWidget *widget = new QWidget(mdiArea);
    // Adding layout to it
    QGridLayout *gridLayout = new QGridLayout(widget);
    widget->setLayout(gridLayout);
    // Adding an label to the widget
    QLabel *label = new QLabel("Hello, I am sub window!!!", widget);
    gridLayout->addWidget(label);

    // Adding a widget as a sub window in the Mdi Area
    mdiArea->addSubWindow(widget);
    // Set the window title
    widget->setWindowTitle("Sub Window");
    // And show the widget
    widget->show();
}

Download the project with an example QMdiArea

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
ДЛ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
СЦ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
AT

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
J
JonnyJoMarch 30, 2023, 9:57 p.m.
Qt/C++ - Lesson 021. The drawing mouse in Qt Евгений, здравствуйте! Только начал изучение Qt и возник вопрос по 21ому уроку. После написания кода, выдаёт следующие ошибки В чём может быть проблема?
АН
Алексей НиколаевMarch 26, 2023, 7:10 p.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Добрый день, взял за основу ваш PopUp notification , и немного доработал его под свои нужды. Добавил в отдельном eventloop'e всплывающую очередь уведомлений с анимацией и таймеро…
АН
Алексей НиколаевMarch 26, 2023, 7:04 p.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Включите прозрачность в композит менеджере fly-admin-theme : fly-admin-theme ->Эффекты и всё заработает.
NSProject
NSProjectMarch 25, 2023, 12:35 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Да не я так к примеру просто написал.
Evgenii Legotckoi
Evgenii LegotckoiMarch 24, 2023, 8:09 p.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Почитайте эту статью про "хлебные крошки"
Now discuss on the forum
BlinCT
BlinCTApril 1, 2023, 3:16 p.m.
Нужен совет по работе с ListView и несколькими моделями Спасибо, сейчас займусь этим.
NSProject
NSProjectMarch 31, 2023, 12:55 p.m.
Проверка комментария принадлежит он пользователю или нет DRF (Django Rest Framework) Здравствуйте! Сегодня я столкнулся с такой проблеммой. Существует модель комметариев. Где их соответственно достаточное количество. Все они выводятся при помощи запроса ajax (axios). Так ка…
P
PisychMarch 30, 2023, 12:50 p.m.
Как подсчитать количество по условию? Да! Вот так работает! Огромное Вам спасибо! ........
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 2:11 p.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
ВА
Виталий АнисимовJan. 30, 2023, 2:17 a.m.
Как добавить виртуальную клавиатура с Т9 в своей проект на QML. Добрый день. Прошу помочь, пишу небольше приложение в Qt. Добвил в свой проект виртуальную клавиатуру от Qt. Но как добавить в него возможность изменения Т9 никак не могу понять.

Follow us in social networks