Search code examples
qtqt4qt5qtgui

How to create a multi window Qt application


I have a mainwindow application created from qt widget.

Now I want to add a child window to this mainwindow so that I can switch the main window and child window continously


Solution

  • First, make a new project with Qt then Right click on project name -> Add new... and make a new UI class like this images: image one , image two

    Now you have two forms. You need to make an object from the Second class in First.

    first.h:

    #ifndef FIRST_H
    #define FIRST_H
    
    #include <QMainWindow>
    #include <second.h>
    #include <QTimer>
    
    namespace Ui {
    class First;
    }
    
    class First: public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit First(QWidget *parent = 0);
        ~First();
    
    private slots:
        void on_pushButton_clicked();
        void changeWindow();
    
    private:
        Ui::First *ui;
        Second *second;
        QTimer * timer;
    };
    
    #endif // FIRST_H
    

    first.cpp:

    #include "first.h"
    #include "ui_first.h"
    
    First::First(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::First)
    {
        ui->setupUi(this);
    
        second = new Second();
        timer = new QTimer();
        connect(timer,&QTimer::timeout,this,&First::changeWindow);
        timer->start(1000); // 1000 ms
    }
    
    First::~First()
    {
        delete ui;
    }
    
    void First::changeWindow()
    {
        if(second->isVisible())
        {
            second->hide();
            this->show();
        }
        else
        {
            this->hide();
            second->show();
        }
    }
    
    void First::on_pushButton_clicked()
    {
        second->show();
    }
    

    first.pro:

    QT       += core gui 
    
    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
    
    TARGET = First
    TEMPLATE = app
    
    
    SOURCES += main.cpp\
            first.cpp \
        second.cpp
    
    HEADERS  += first.h \
        second.h
    
    FORMS    += first.ui \
        second.ui
    

    First form ui