1.自定义信号和槽
以下仅列出修改过的文件:
1.teacher.h
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
signals:
// 自定义信号;
// 返回值void,只需要声明,不需要实现;
// 可以有参数,可以重载
void hungry();
public slots:
};
#endif // TEACHER_H
2.student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
class Student : public QObject
{
Q_OBJECT
public:
explicit Student(QObject *parent = nullptr);
signals:
public slots:
//高版本槽函数可以写到public或者全局下
//返回值void,需要声明,需要实现
//可以有参数,可以重载
void treat();
};
#endif // STUDENT_H
3.student.cpp
#include "student.h"
#include<QDebug>
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::treat()
{
qDebug()<<"请老师吃饭!";
}
4.widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include"teacher.h"
#include"student.h"
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
Teacher *tea;
Student *stu;
void classIsOver();
};
#endif // WIDGET_H
5.widget.cpp
#include "widget.h"
#include "ui_widget.h"
//创建老师类和学生类,下课后老师触发信号饿了,学生响应请吃饭
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->tea=new Teacher(this);
this->stu=new Student(this);
connect(tea,&Teacher::hungry,stu,&Student::treat);
classIsOver();//先连接,后调用信号
}
void Widget::classIsOver()
{
//下课函数,触发老师饿了信号
emit tea->hungry();//触发关键字emit
}
Widget::~Widget()
{
delete ui;
}
2 自定义信号和槽发生重载
void Student::treat(QString foodName)
{
//QString 转换成 char*,先转换成 QByteArray (.toUtf8()) 然后转换 char* (.data())
//qDebug()<<"请老师吃"<<foodName; //输出:请老师吃 "宫保鸡丁"
qDebug()<<"请老师吃"<<foodName.toUtf8().data();//输出:请老师吃 宫保鸡丁
}
void Widget::classIsOver()
{
//下课函数,触发老师饿了信号
emit tea->hungry();//触发关键字emit
emit tea->hungry("宫保鸡丁");
}
//函数指针 函数返回值类型 (* 指针变量名) (函数参数列表);
void(Teacher:: *teacherSignal)(QString)=&Teacher::hungry;
void(Student:: *studentSlot)(QString)=&Student::treat;
connect(tea,teacherSignal,stu,studentSlot);
classIsOver();