赞
踩
初学QT,记录一下该作业
当按下按钮后,从窗口1切换到窗口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里这样做很傻!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。