Evgenii Legotckoi
April 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.

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QMdiArea>
  6.  
  7. namespace Ui {
  8. class MainWindow;
  9. }
  10.  
  11. class MainWindow : public QMainWindow
  12. {
  13. Q_OBJECT
  14.  
  15. public:
  16. explicit MainWindow(QWidget *parent = 0);
  17. ~MainWindow();
  18.  
  19. private slots:
  20. void on_actionAddWindow_triggered();
  21.  
  22. private:
  23. Ui::MainWindow *ui;
  24. QMdiArea * mdiArea; // Area in which windows will be added
  25. };
  26.  
  27. #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.

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3.  
  4. #include <QGridLayout>
  5. #include <QLabel>
  6.  
  7. MainWindow::MainWindow(QWidget *parent) :
  8. QMainWindow(parent),
  9. ui(new Ui::MainWindow)
  10. {
  11. ui->setupUi(this);
  12. mdiArea = new QMdiArea(this); // init QMdiArea
  13. // configure scrollbars
  14. mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  15. mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  16.   // Set Mdi Area as the central widget
  17. setCentralWidget(mdiArea);
  18. }
  19.  
  20. MainWindow::~MainWindow()
  21. {
  22. delete ui;
  23. }
  24.  
  25. void MainWindow::on_actionAddWindow_triggered()
  26. {
  27.   // Create a widget that will be a window
  28. QWidget *widget = new QWidget(mdiArea);
  29. // Adding layout to it
  30. QGridLayout *gridLayout = new QGridLayout(widget);
  31. widget->setLayout(gridLayout);
  32.   // Adding an label to the widget
  33. QLabel *label = new QLabel("Hello, I am sub window!!!", widget);
  34. gridLayout->addWidget(label);
  35.  
  36.   // Adding a widget as a sub window in the Mdi Area
  37. mdiArea->addSubWindow(widget);
  38.   // Set the window title
  39. widget->setWindowTitle("Sub Window");
  40.   // And show the widget
  41. widget->show();
  42. }

Download the project with an example QMdiArea

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html