开发者

How to move to another window in Qt by a pushbutton

I am using Qt Creator 2.0.1 b开发者_JAVA技巧ased 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?


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.


You'll achieve it by using signals and slots mechanism. You just show another window when pushButton is clicked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜