How to create a multi window Qt application

VamsiKrishna Neelam picture VamsiKrishna Neelam · Jul 10, 2017 · Viewed 11.6k times · Source

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

Answer

Farhad picture Farhad · Jul 10, 2017

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 a object from 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();
}

fisrt.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