1、 實例需求
從MainWindow窗體點擊按鈕打開MainWindow2窗體。
2、 實例實現
第一步:創建完項目之後,在點擊 文件-新建文件或項目-文件和類-Qt-Qt 設計師界面類 如圖1.1
單擊選擇彈出圖1.2
單擊下一步,彈出圖1.3
單擊下一步,彈出圖1.3
單擊完成,此時項目中又多了一個MainWindow2窗體。
第二步:打開MainWindow.h 頭文件,編寫代碼。
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
//add by dx ---20180826
#include <QPushButton>
#include "mainwindow2.h"
//end by dx
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
//add by dx ---20180826
protected:
QPushButton *pButton;
MainWindow2 w2;
private slots:
void showMainWindow2();
//end by dx
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
打開MainWindow.cpp文件,編寫代碼。
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//add by dx ---20180826
//設置窗體標題
this->setWindowTitle("窗口一");
//定義按鈕
pButton = new QPushButton(this);
pButton->setText("打開窗口2");
//關聯
connect(pButton,SIGNAL(clicked(bool)),this,SLOT(showMainWindow2()));
//end by dx
}
MainWindow::~MainWindow()
{
delete ui;
}
//add by dx ---20180826
void MainWindow::showMainWindow2()
{
w2.show();
}
//end by dx
打開MainWindow2.cpp文件,編寫代碼:
#include "mainwindow2.h"
#include "ui_mainwindow2.h"
MainWindow2::MainWindow2(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow2)
{
ui->setupUi(this);
//add by dx ---20180826
//設置窗體標題
this->setWindowTitle("窗體二");
//end by dx
}
MainWindow2::~MainWindow2()
{
delete ui;
}
3、 效果圖
今天講解到現在結束了,想進行視頻學習的小夥伴,可以進入我的視頻教程進行學習,課程地址:https://edu.csdn.net/course/detail/7275,課程資源下載地址:https://download.csdn.net/download/xuan_xuan_2/10641568,歡迎大家前來學習交流。