学习分享
1、环境设置,头文件
该示例使用C++14实现,因此在QT项目pro文件中修改配置
使用智能指针实现,需要的头文件为:
cpp
#include <memory>
2、.h文件
2.1、主界面.h文件
cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStackedLayout>
#include "dialogq.h"
#include "dialogw.h"
#include <memory>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
QStackedLayout * layout;
std::unique_ptr<Dialogq> dialog11;
std::unique_ptr<Dialogw> dialog22;
};
#endif // MAINWINDOW_H
2.2、对话界面1.h文件
cpp
#ifndef DIALOGQ_H
#define DIALOGQ_H
#include <QWidget>
namespace Ui {
class Dialogq;
}
class Dialogq : public QWidget
{
Q_OBJECT
public:
explicit Dialogq(QWidget *parent = nullptr);
~Dialogq();
private:
Ui::Dialogq *ui;
};
#endif // DIALOGQ_H
2.3、对话界面2.h文件
cpp
#ifndef DIALOGW_H
#define DIALOGW_H
#include <QWidget>
namespace Ui {
class Dialogw;
}
class Dialogw : public QWidget
{
Q_OBJECT
public:
explicit Dialogw(QWidget *parent = nullptr);
~Dialogw();
private:
Ui::Dialogw *ui;
};
#endif // DIALOGW_H
3、.cpp文件
3.1、对话界面1.cpp
cpp
#include "dialogq.h"
#include "ui_dialogq.h"
Dialogq::Dialogq(QWidget *parent) :
QWidget(parent),
ui(new Ui::Dialogq)
{
ui->setupUi(this);
}
Dialogq::~Dialogq()
{
delete ui;
}
3.2、对话界面2.cpp
cpp
#include "dialogw.h"
#include "ui_dialogw.h"
Dialogw::Dialogw(QWidget *parent) :
QWidget(parent),
ui(new Ui::Dialogw)
{
ui->setupUi(this);
}
Dialogw::~Dialogw()
{
delete ui;
}
3.3、主界面.cpp
cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStackedLayout>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->dialog11 =std::make_unique<Dialogq>();
this->dialog22 =std::make_unique<Dialogw>();
this->layout =new QStackedLayout(ui->frame);
this->layout->addWidget(dialog11.get());
this->layout->addWidget(dialog22.get());
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
this->layout->setCurrentWidget(dialog11.get());
}
void MainWindow::on_pushButton_2_clicked()
{
this->layout->setCurrentWidget(dialog22.get());
}
3.4、main.cpp
cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}