Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move to another window in Qt by a pushbutton

Tags:

qt4

I am using Qt Creator 2.0.1 based on Qt 4.7.0 (32bit). I am new to Qt.

I created a mainwindow. How do I go to another window when I press the pushbutton in the main window?

like image 506
Yamuna mathew Avatar asked Feb 26 '23 01:02

Yamuna mathew


1 Answers

I am able to do it well. I just give the code for anyone who need this. I have a window called MainWindow and a NewWindow. I have a button in Mainwindow called mMyButton. mainwindow.h is as follows.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>

//added
#include"newwindow.h"

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    //added
    public slots:
       void openNewWindow();

    //added name of the new window is NewWindow
    private:
       NewWindow *mMyNewWindow;

    private:
        Ui::MainWindow *ui;

    private slots:
        void on_mMyButton_clicked();
};
#endif // MAINWINDOW_H

My newwindow.h is as follows.

#ifndef NEWWINDOW_H
#define NEWWINDOW_H

#include <QMainWindow>

namespace Ui {
    class NewWindow;
}

class NewWindow : public QMainWindow
{
    Q_OBJECT

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

    private:
        Ui::NewWindow *ui;
};

#endif // NEWWINDOW_H

My mainwindow.cpp is as follows.

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //Added
    connect(ui->mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
}

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

void MainWindow::openNewWindow()
{
    mMyNewWindow = new NewWindow();

    mMyNewWindow->show();

}

void MainWindow::on_mMyButton_clicked()
{
    openNewWindow();
}

My newwindow.cpp,

#include "newwindow.h"
#include "ui_newwindow.h"

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

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

My main.cpp as,

 #include <QtGui/QApplication>
 #include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Thanks for all the information. And enjoy the programming with Qt.

like image 146
Yamuna Mathew Avatar answered Mar 08 '23 08:03

Yamuna Mathew