一、槽和信号
connect(信号的发送者,发送的具体信号,信号的接收者,信号的处理(槽))
- 信号槽的优点:
松散耦合,即信号端和接收端本身是没有关联的,通过connect连接将两端耦合在一起。
二、自定义信号和槽
1、自定义信号
- 在信号的发送者的.h下面的signals定义
- 返回 void
- 需要声明,不需要实现
- 可以有参数,可以重载
2、自定义槽函数
- 写到信号的接受者.h的public slot 或 public 或全局函数
- 返回void
- 需要声明,需要实现
- 可以有参数,可以重载
3、触发自定义的信号
- emit +自定义信号
4、案例
- 下课后,老师触发饿的信号,学生响应信号,请客吃饭
- Student.h
#include <QObject>
class Student : public QObject
{
Q_OBJECT
public:
explicit Student(QObject *parent = nullptr);
signals:
public slots:
//槽函数
void treat();
};
- Teacher.h
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
signals:
//发送者的信号
void hungry();
public slots:
};
- mywindow.h
class MyWindow : public QWidget
{
Q_OBJECT
public:
MyWindow(QWidget *parent = nullptr);
~MyWindow();
private:
Ui::MyWindow *ui;
Teacher *tea;
Student *stu;
void classIsOver();
};
- student.cpp
void Student::treat()
{
qDebug()<<"eat!!!!";
}
- mywindow.cpp
MyWindow::MyWindow(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MyWindow)
{
ui->setupUi(this);
//创建老师和学生对象
//(this)是指父对象,便于回收
this->tea = new Teacher(this);
this->stu = new Student(this);
connect(tea,&Teacher::hungry,stu, &Student::treat);
//调用函数,触发信号
classIsOver();
}
void MyWindow::classIsOver()
{
emit tea->hungry();
}