自定义信号和槽

student.h

 1 #ifndef STUDENT_H
 2 #define STUDENT_H
 3 
 4 #include <QObject>
 5 
 6 class Student : public QObject
 7 {
 8     Q_OBJECT
 9 public:
10     explicit Student(QObject *parent = 0);
11 
12 signals:
13 
14 public slots:
15     //早期Qt版本,必须要写道public slots 下高级版本可以写道public或者全局下
16     //返回值 void ,需要声明 , 也需要实现
17     //可以有参数,可以发生重载
18     void treat();
19 };
20 
21 #endif // STUDENT_H

teacher.h

 1 #ifndef TEACHER_H
 2 #define TEACHER_H
 3 #include <QObject>
 4 
 5 class Teacher : public QObject
 6 {
 7     Q_OBJECT
 8 public:
 9     explicit Teacher(QObject *parent = 0);
10 
11 signals:
12     //自定义信号  写到signals下
13     //返回值是void , 只需要声明  , 不需要实现
14     //可以有参数 , 可以有重载
15     void hungry();
16 
17 public slots:
18 };
19 
20 #endif // TEACHER_H

widget.h

 1 #ifndef WIDGET_H
 2 #define WIDGET_H
 3 #include "teacher.h"
 4 #include "student.h"
 5 #include <QWidget>
 6 
 7 class Widget : public QWidget
 8 {
 9     Q_OBJECT
10 
11 public:
12     Widget(QWidget *parent = 0);
13     ~Widget();
14 private:
15     //对  对象以及下课 方法进行声明
16     Teacher *lz;
17     Student *jj;
18     void classIsOver();
19 
20 };
21 
22 #endif // WIDGET_H

student.cpp

 1 #include "student.h"
 2 #include "QDebug"
 3 Student::Student(QObject *parent) : QObject(parent)
 4 {
 5 
 6 }
 7 //对声明的请客方法进行实现
 8 void Student::treat()
 9 {
10     //可以用qDebug方法 输出一句话
11     qDebug()<<"请老师吃饭";
12 }

teacher.cpp

1 #include "teacher.h"
2 
3 Teacher::Teacher(QObject *parent) : QObject(parent)
4 {
5 
6 }

widget.cpp

 1 #include "widget.h"
 2 
 3 Widget::Widget(QWidget *parent)
 4     : QWidget(parent)
 5 {
 6     //创建老师和学上对象  其中 new Teacher(this) 中的this 指对象是widget 的子类 
 7     this->lz = new Teacher(this);
 8     this->jj = new Student(this);
 9     //老师饿了学生请吃饭 信号槽的连接
10     connect(lz,&Teacher::hungry,jj,&Student::treat);
11     //调用 下课 方法  触发信号
12     classIsOver();
13 
14 }
15 
16 Widget::~Widget()
17 {
18 
19 }
20 void Widget ::classIsOver()
21 {
22     // emit 可以用来触发信号
23     emit lz->hungry();
24 }
posted @ 2020-01-10 15:28  不识人间花火  阅读(414)  评论(0编辑  收藏  举报