工程目录
//main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
//mywidget.cpp 子窗口,在主窗口中作为属性,可以被new和delete
#include "mywidget.h"
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
//子窗口只有一个close button,可以自定义子窗口,这一段内容可以删去
QPushButton * closeBtn = new QPushButton("CLOSE",this);
closeBtn->move(200,100);
connect(closeBtn, &QPushButton::clicked,this,&QWidget::close);
resize(600,400);
}
MyWidget::~MyWidget()
{
}
//widget.cpp
//主窗口
#include "widget.h"
#include "MyWidget.h"
#include "stdlib.h"
//新建一个子窗口
void Widget::createSonWin(){
disconnect(Btn, &QPushButton::clicked,this,&Widget::createSonWin); //取消按键与新建窗口的链接
connect(Btn, &QPushButton::clicked,this,&Widget::closeSonWin); //链接按键与关闭窗口
Btn->setText("close"); //修改按键名为close
this->myWin = new MyWidget; //新建窗口
myWin->show(); //展示窗口
}
//关闭子窗口,与上面的新建类似
void Widget:: closeSonWin(){
disconnect(Btn, &QPushButton::clicked,this,&Widget::closeSonWin);
connect(Btn, &QPushButton::clicked,this,&Widget::createSonWin);
Btn->setText("open");
myWin->close();
delete(this->myWin);
}
//主窗口构造函数
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
//新建一个btn按钮并链接到打开子窗口
Btn = new QPushButton("OPEN",this);
Btn->move(100,100);
//链接按钮与新建子窗口
connect(Btn, &QPushButton::clicked,this,&Widget::createSonWin);
resize(600,400);
}
Widget::~Widget()
{
delete ui;
}
//子窗口类头文件
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QPushButton>
#include <QDebug>
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = nullptr);
~MyWidget();
signals:
};
#endif // MYWIDGET_H
//主窗口类头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
#include <QDebug>
#include "MyWidget.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void createSonWin();
void closeSonWin();
MyWidget * myWin;
QPushButton * Btn;
private:
Ui::Widget *ui;
};
#endif // WIDGET_H