QT自定义信号和槽实现
student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
class Student : public QObject
{
Q_OBJECT
public:
explicit Student(QObject *parent = nullptr);
//返回值 void,需要声明,也需要实现
//可以有参数,可以重载
void treat();
signals:
//早期版本必须写到public slots下,高级版本可以写到public或者全局下
};
#endif // STUDENT_H
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
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include"teacher.h"
#include"student.h"
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Teacher*zt;
Student *st;
void classIsOver();
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
student.cpp
#include "student.h"
#include<QDebug>
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::treat()
{
qDebug()<<"请老师吃饭";
}
teacher.cpp
#include "teacher.h"
Teacher::Teacher(QObject *parent) : QObject(parent)
{
}
widget.cpp
#include "widget.h"
//Teacher 类 老师类
//Student 类 学生类
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
//创建一个老师对象
this->zt = new Teacher(this);
//创建一个学生对象
this->st = new Student(this);
//连接
connect(zt,&Teacher::hungry,st,&Student::treat);
//调用下课函数
classIsOver();
}
void Widget::classIsOver()
{
//下课后,触发信号
emit zt->hungry();
}
Widget::~Widget()
{
}