QT点击按钮打开和关闭子窗口

QT点击按钮打开和关闭子窗口

1、功能描述

在主窗口上点击一个按钮生成一个新的窗口,并同时生成另外一个按钮实现点击关闭新窗口的功能。

2、两个按钮实现

  • widget.h
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPushButton>

class Widget : public QWidget
{
    
    
    Q_OBJECT
private:
    QPushButton *btn1;
    QPushButton *btn2;
    QWidget *new_widget;
public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
};
#endif // WIDGET_H
  • widget.cpp
#include "widget.h"
#include <QApplication>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    
    
    //创建两个按钮
    btn1 = new QPushButton("OPEN",this);
    btn2 = new QPushButton("CLOSE",this);
    btn2->move(100,0);

    //设置主窗口标题
    setWindowTitle("主窗口");

    //创建一个子窗口
    new_widget = new QWidget;

    //设置子窗口标题
    new_widget->setWindowTitle("子窗口");

    //重置窗口大小
    resize(600,500);

    connect(btn1,&QPushButton::clicked,new_widget,&Widget::show);
    connect(btn2,&QPushButton::clicked,new_widget,&Widget::close);

}

Widget::~Widget()
{
    
    
}
  • main.cpp
#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

在这里插入图片描述

3、一个按钮实现

  • widget.h
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPushButton>

class Widget : public QWidget
{
    
    
    Q_OBJECT
private:
    QPushButton *btn;
    QWidget *new_widget;
public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
};
#endif // WIDGET_H

  • widget.cpp
#include "widget.h"
#include <QApplication>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    
    
    //创建按钮
    btn = new QPushButton("OPEN",this);

    //设置主窗口标题
    setWindowTitle("主窗口");

    //创建一个子窗口
    new_widget = new QWidget;

    //设置子窗口标题
    new_widget->setWindowTitle("子窗口");

    //重置窗口大小
    resize(600,500);

    connect(btn, &QPushButton::clicked, new_widget, [=](){
    
    
        if(btn->text() == "OPEN")
        {
    
    
            btn->setText("CLOSE");
            new_widget->show();
        }
        else if(btn->text() == "CLOSE")
        {
    
    
            btn->setText("OPEN");
            new_widget->close();
        }
    });
}

Widget::~Widget()
{
    
    
}
  • main.cpp
#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43762434/article/details/133157788