Qt's signal and slot case

        In Qt, the signal generator and the signal receiver are bound together by connect(). The format is as follows:
        connect (signal generator, generated signal, signal receiver, processing function)
        gives a student to invite the teacher to eat, use the signal and The slot mechanism is implemented.
        Software requirements: Create two teacher classes. After the Student
        class is over, the teacher zt will send a signal : hungry(); the
        student responds to the signal Student st. The signal processing slot function : treat ().
As follows:
//1) The main function header file one.h

#ifndef ONE_H
#define ONE_H

#include <QWidget>
#include "teacher.h"
#include "student.h"

class one : public QWidget
{
    
    
    Q_OBJECT

public:
    one(QWidget *parent = 0);
    ~one();

    Teacher *zt;
    Student *st;

    void classIsOver();

};

#endif // ONE_H

//The main function source file one.cpp

#include "one.h"

//需求:创建2个类 Teacher类,Student类
//下课后, 老师Teacher zt 会发出一个信号 饿了
//学生响应信号Student st 处理信号的槽函数 请客吃饭




one::one(QWidget *parent)
    : QWidget(parent)
{
    
    
    zt = new Teacher(this);
    st = new Student(this);

    //连接 老师和学生
    connect(zt,&Teacher::hungry,st,&Student::treat );
    classIsOver();
}

one::~one()
{
    
    

}

void one::classIsOver()
{
    
    
    //触发老师饿了的信号
    emit zt->hungry();
}

//2) Student.h header file

#ifndef STUDENT_H
#define STUDENT_H

#include <QObject>

class Student : public QObject
{
    
    
    Q_OBJECT
public:
    explicit Student(QObject *parent = 0);

signals:

public slots:
    //自定义槽函数
    //槽函数和信号匹配
    void treat();

};

#endif // STUDENT_H

//Student source file Student.cpp

#include "student.h"
#include <QDebug>

Student::Student(QObject *parent) :
    QObject(parent)
{
    
    
}

void Student::treat()
{
    
    
    qDebug()<<"请老师吃饭";
}

//3) Teacher class header file Student.h

#ifndef TEACHER_H
#define TEACHER_H

#include <QObject>

class Teacher : public QObject
{
    
    
    Q_OBJECT
public:
    explicit Teacher(QObject *parent = 0);

signals:
    //自定义的信号,需要写到signals下
    //返回类型必须为空,信号只需要声明,不需要实现
    //信号可以有参数,可以重载
    void hungry();

public slots:

};

#endif // TEACHER_H

//Teacher source file Student.cpp

#include "teacher.h"

Teacher::Teacher(QObject *parent) :
    QObject(parent)
{
    
    
}

        The effect is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/sanqima/article/details/103844124