0
点赞
收藏
分享

微信扫一扫

QT学习分享(6)-------打开和关闭一个新界面

爱读书的歌者 2022-03-14 阅读 46

QT学习分享(6)-------打开和关闭一个新界面

1、UI设计

在这里插入图片描述

2、思路

设置一个整数型变量,当子窗口打开时为1,关闭时为0,由此来控制槽函数的功能

3、代码

3.1 sonWin.h

#pragma once
#include <QtWidgets/QMainWindow>
class sonWin : public QWidget
{
    Q_OBJECT;
public:
    sonWin(QWidget* parent = Q_NULLPTR);

};

3.2 sonWin.cpp

#include "sonWin.h"

// 防止中文乱码代码
#ifdef WIN32
#pragma execution_character_set("utf-8")  
#endif

sonWin::sonWin(QWidget* parent) : QWidget(parent)
{
    this->setWindowTitle("子窗口");
    this->resize(300, 300);

}

3.3 test1.h

#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_test1.h"
#include "sonWin.h"

class test1 : public QMainWindow
{
    Q_OBJECT
public:
    test1(QWidget *parent = Q_NULLPTR);
    int flag = 0; // 控制信号
    sonWin son1; // 实例化子窗口


private:
    Ui::test1Class ui;

public slots:
    void openotherwin();  // 函数声明
};

3.4 test1.cpp

#include "test1.h"
#include "sonWin.h"
#ifdef WIN32 
#pragma execution_character_set("utf-8")  
#endif

test1::test1(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    setWindowTitle("打开窗口界面");
    connect(ui.but1, SIGNAL(clicked()), this,SLOT(openotherwin()));
}

void test1::openotherwin()
{
    if (flag == 0)
    {
        son1.show();
        flag = 1;
        ui.but1->setText("关闭");
    }
    else
    {
        son1.hide();
        ui.but1->setText("打开");
        flag = 0;
    }
}

3.5 main.cpp

#include "test1.h"
#include <QtWidgets/QApplication>

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

4、结果展示

在这里插入图片描述

在这里插入图片描述

举报

相关推荐

0 条评论