自定义信号和槽函数
案例背景:
老师->饿了信号 学生 ->请老师吃饭
设计两个类:老师类 学生类
添加类的步骤:
工程---->添加新文件---->添加class类---->基于QObject添加类
定义信号和槽的规则
1、定义信号的规则:在signal下方
返回值类型为void,只需声明,不需实现,可以有参数,可以重载
2、定义槽函数的规则:在slots下方
返回值类型为void,需要声明,也需要实现,可以有参数,可以重载
3、用户可以使用emit发出信号
代码
student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
#include <QString>
class Student : public QObject
{
Q_OBJECT
public:
explicit Student(QObject *parent = nullptr);
signals:
public slots:
//在下方自定义槽函数---发起者不用写槽
void treat();
void treat(QString FoodName);
};
#endif // STUDENT_H
teacher.h
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
#include <QString>
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
signals:
//在下方自定义信号函数
//返回值类型为void,只需声明,不需实现,可以有参数,可以重载
void hungry();
//信号发出的参数会被槽函数接收
void hungry(QString FoodName);
public slots:
//在下方自定义槽函数---发起者不用写槽
};
#endif // TEACHER_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
};
#endif // WIDGET_H
student.cpp
#include "student.h"
#include <QDebug>
//#include <string>
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::treat()
{
qDebug()<<"treat my teacher"<<endl;
}
void Student::treat(QString FoodName)
{
qDebug()<<"treat my teacher"<<FoodName<<endl;
}
teacher.cpp
#include "teacher.h"
Teacher::Teacher(QObject *parent) : QObject(parent)
{
}
widget.cpp
#include "widget.h"
#include "teacher.h"
#include "student.h"
#include <QPushButton>
#define N 0
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
//设置主窗口大小
this->resize(800,600);
//实例化一个老师
Teacher *tea = new Teacher(this);
//实例化一个学生
Student *stu = new Student(this);
#if N
//connect
//connect(tea,&Teacher::hungry,stu,&Student::treat);
void (Teacher::*p1)()=&Teacher::hungry;
void (Student::*p2)()=&Student::treat;
connect(tea,p1,stu,p2);
#else
//报错的原因,hungry被重载了
//通过函数指针,明确哪个函数
void (Teacher::*p1)(QString FoodName)=&Teacher::hungry;
void (Student::*p2)(QString FoodName)=&Student::treat;
connect(tea,p1,stu,p2);
#endif
//下课了,老师饿了
QPushButton *btn= new QPushButton("sit down",this);
connect(btn,&QPushButton::clicked,[=](){
//下课函数
//让老师发出饿的信号
#if N
emit tea->hungry(); //槽函数会接收meat
#else
emit tea->hungry("meat");//槽函数会接收meat
#endif
});
}
Widget::~Widget()
{
}
总结:
1、一个信号可以与多个槽相连;
2、多个信号可以连接到一个槽;
3、一个信号剋连接到另一个信号;