当前位置:   article > 正文

C++ QT 用按钮切换两个窗口_qt如何调用子窗口

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/730667
推荐阅读
相关标签
  

闽ICP备14008679号