信号与槽源码:举例(下课了请老师吃饭+地震了动物跑了人也跑了)
dialog源文件:
#include "dialog.h"
#include "ui_dialog.h"
#include "QDebug"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
teacher = new Teacher();
student = new Student();
connect(teacher , SIGNAL(hungry()) , student , SLOT(eat()));
afterClass();
connect(&animal , SIGNAL(animalRun()) , &people , SLOT(peopleRun()));
theWorldEnd();
}
Dialog::~Dialog()
{
delete ui;
}
void Student::eat()
{
qDebug()<<"请张老师吃饭";
}
void Dialog::afterClass()
{
qDebug()<<"下课了";
emit teacher->hungry();
}
//connect(信号的发送者,发送的具体的信号,信号的接收者,对接收的信号进行处理)
//信号的发送者和信号的接收者是一个对象(引用、指针)
//发送的具体的信号和对接收的信号进行处理都是函数
//实现自定义信号与槽
//例子:下课了 张老师 饿了 学生 请张老师吃饭
void Dialog::theWorldEnd()
{
qDebug()<<"世界末日来了";
emit animal.animalRun();
}
dialog头文件:
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include "people.h"
#include "animal.h"
namespace Ui {
class Dialog;
}
class Teacher :public QObject
{
Q_OBJECT
signals:
void hungry();
};
class Student : public QObject
{
Q_OBJECT
public slots:
void eat(); //槽函数
};
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = nullptr);
~Dialog();
void afterClass();//下课了,在这个方法里面用emit+信号,将信号发送出来
void theWorldEnd();//世界末日
private:
Ui::Dialog *ui;
Teacher *teacher;
Student *student;
People people;
Animal animal;
};
#endif // DIALOG_H
animal源文件:
#include "animal.h"
Animal::Animal(QObject *parent) : QObject(parent)
{
}
animal头文件:
#ifndef ANIMAL_H
#define ANIMAL_H
#include <QObject>
class Animal : public QObject
{
Q_OBJECT
public:
explicit Animal(QObject *parent = nullptr);
signals:
void animalRun(); //信号
public slots:
};
#endif // ANIMAL_H
people源文件:
#include "people.h"
#include <QDebug>
People::People(QObject *parent) : QObject(parent)
{
}
void People::peopleRun()
{
qDebug()<<"人也逃走了";
}
people头文件:
#ifndef PEOPLE_H
#define PEOPLE_H
#include <QObject>
class People : public QObject
{
Q_OBJECT
public:
explicit People(QObject *parent = nullptr);
signals:
public slots:
void peopleRun();
};
#endif // PEOPLE_H
main主函数文件:
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}