How to switch to another window in Qt using the button

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

I created the main window. How to switch to another window when I click the button in the main window?

+4
source share
2 answers

I can do it well. I just give the code to everyone who needs it. I have a window called MainWindow and NewWindow . I have a button in MainWindow called mMyButton . mainwindow.h 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 info. And enjoy programming with Qt.

+7
source

You will achieve this using the signal and slot mechanism . You simply show another window when the PushButton button is pressed.

0
source

Source: https://habr.com/ru/post/1340152/


All Articles