C++ QT 用按钮切换两个窗口

初学QT,记录一下该作业
主窗口
当按下按钮后,从窗口1切换到窗口2
窗口2
当按下按钮后,从窗口2切换到窗口1
窗口1是主窗口,继承于QMainWindow
窗口2是子窗口,继承于QWidget
从继承关系上看,窗口1和窗口2是独立的子窗口。

用信号和槽机制完成动作触发。
窗口2是窗口1的保护成员。
窗口2的按钮是窗口2的保护成员。
而连接动作写在了窗口1的构造函数(为了方便,自认为符合面向对象思维),所以有个问题就是要通过窗口1实例访问窗口2的按钮,但窗口2的按钮并不是public类型,所以用了很笨的方法,以下是代码。
sonwindow.h(子窗口,son打错了)

#ifndef SONWINDOW_H
#define SONWINDOW_H

#include <QWidget>
#include <QPushButton>
class sonwindow : public QWidget
{
    Q_OBJECT
public:
    explicit sonwindow(QWidget *parent = nullptr);
    const QPushButton *GetReadOnlyButton();
private:
    QPushButton *b;

signals:

public slots:
};

#endif // SONWINDOW_H

windows.h(主窗口)

#ifndef WINDOWS_H
#define WINDOWS_H

#include <QMainWindow>
#include "sonwindow.h"
#include <QPushButton>
class Windows : public QMainWindow
{
    Q_OBJECT
private:
    sonwindow sw;
    QPushButton *b;

public:
    Windows(QWidget *parent = 0);
    ~Windows();
};

#endif // WINDOWS_H

sonwindow.cpp

#include "sonwindow.h"
#include <QPushButton>
sonwindow::sonwindow(QWidget *parent) : QWidget(parent)
{
    b = new QPushButton("点老子切换窗口1",this);
    b->setGeometry(10,10,200,200);
    this->resize(800,600);
    this->setWindowTitle("窗口2");
}

const QPushButton *sonwindow::GetReadOnlyButton()
{
    return (const QPushButton *)b;
}

windows.cpp

#include "windows.h"
#include "QPushButton"
Windows::Windows(QWidget *parent)
    : QMainWindow(parent)
{
    b = new QPushButton("点老子切换窗口2",this);
    b->setGeometry(10,10,200,200);
    this->resize(800,600);
    this->setWindowTitle("窗口1");
    //建立连接

    connect(b,&QPushButton::clicked,[=](){

        this->hide();
        this->sw.show();

    });

    connect(this->sw.GetReadOnlyButton(),&QPushButton::clicked,[=](){

        this->show();
        this->sw.hide();

    });

}

Windows::~Windows()
{

}

为了在窗口1的构造函数访问到窗口2的按钮,多设置了一个GetReadOnlyButton函数,强转为const*类型并返回,这样既没有改变实例的地址,又可以通过编译器的限制,让窗口1不能修改窗口2的按钮(独立关系),虽然这样做功能实现了,但直觉上总感觉在QT里这样做很傻!

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值