student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
class Student : public QObject
{
Q_OBJECT
public:
explicit Student(QObject *parent = nullptr);
//槽函数可以写到public下
//返回值是void,需要声明,也需要实现
//可以有参数,可以发生重载
void treat();
signals:
};
#endif // STUDENT_H
student.cpp
#include "student.h"
#include <QDebug>
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::treat()
{
qDebug() << "请老师吃饭";
}
teacher.h
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
signals:
//自定义信号写到signals下
//返回值是void,只需要声明,不需要实现
//可以有参数,可以重载
void hungry();
};
#endif // TEACHER_H
teacher.cpp
#include "teacher.h"
Teacher::Teacher(QObject *parent) : QObject(parent)
{
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "teacher.h"
#include "student.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
Teacher * teacher1;
Student * student1;
void classIsOver();
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
//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 Widget::classIsOver()
{
//下课函数,调用触发老师饿了的信号
emit teacher1->hungry();
}
Widget::~Widget()
{
delete ui;
}