首先,新建一个Project,名为02_SignalAndSlot,与此同时新建一个widget类。
为了自定义信号和槽,新建两个类:Teacher类,Student类。
【实现需求】老师饿了,说下课,学生请客吃饭
建立的项目结构如下:
解决需求的流程图:
核心代码:
//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:
//槽函数
//返回值为void,需要声明,也需要实现
//可以有参数,可以发生重载
void treat();
};
#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
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "teacher.h"
#include "student.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
Teacher * tea;
Student * stu;
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 "c"
#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();
}
Widget::~Widget()
{
delete ui;
}
运行结果:
学自传智教育,总结并学习,侵删