widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QPushButton>
//Teacher 老师类
//Student 学生类
//下课后,老师会触发信号,饿了,学生响应信号,请客吃饭
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//创建一个老师对象
this->teacher1 = new Teacher(this);
//创建一个学生对象
this->student1 = new Student(this);
// //老师饿了,学生请客的连接
// connect(teacher1, &Teacher::hungry, student1, &Student::treat);
// //调用下课函数
// classIsOver();
//连接带参数的信号和槽
//指针 -> 地址
//函数指针 -> 函数地址
void(Teacher:: *teachersignal)(QString) = &Teacher::hungry;
void(Student:: *studentslot)(QString) = &Student::treat;
//重载函数使用无参函数
//void(Teacher:: *teachersignal)(QString) = &Teacher::hungry;
//void(Student:: *studentslot)(QString) = &Student::treat;
connect(teacher1, teachersignal, student1, studentslot);
//classIsOver();
//点击一个下课的按钮,再触发下课
QPushButton * btn1 = new QPushButton("下课",this);
QPushButton * btn2 = new QPushButton("下课",this);
btn2->move(100,0);
//重置窗口大小
resize(600, 400);
//点击按钮触发下课
connect(btn1, &QPushButton::clicked, this, &Widget::classIsOver);
//无参信号和槽连接
void(Teacher:: *teachersignal2)(void) = &Teacher::hungry;
void(Student:: *studentslot2)(void) = &Student::treat;
connect(teacher1, teachersignal2, student1, studentslot2);
//信号连接信号
connect(btn2, &QPushButton::clicked, teacher1,teachersignal2);
//断开信号
disconnect(teacher1, teachersignal2, student1, studentslot2);
}
void Widget::classIsOver()
{
//下课函数,调用触发老师饿了的信号
emit teacher1->hungry("宫保鸡丁");
//重载函数使用无参函数
//emit teacher1->hungry();
}
Widget::~Widget()
{
delete ui;
}