Qt之信号与槽

student.h:

#ifndef STUDENT_H
#define STUDENT_H

#include <QObject>

class Student:public QObject
{
    Q_OBJECT
public:
    Student();
public slots:
    void  Answer_Queston();
public:
    void Ask_Tech_Question();
signals:
    void stu_signal();
};

#endif // STUDENT_H

student.cpp:

#include "student.h"
#include<QDebug>
Student::Student(){}
 void  Student::Answer_Queston()
 {
     qDebug()<<"I don't know!"<<endl;
 }
void Student::Ask_Tech_Question()
{
   qDebug()<<"Teacher, the question is?"<<endl;
   emit stu_signal();
}

teacher.h:

#ifndef TEACHER_H
#define TEACHER_H
#include<QObject>
class Teacher:public QObject
{
    Q_OBJECT
public:
    Teacher();
    void What_Answer();
signals:
    void tech_signal();
public slots:
    void Answer_stu_Question();
};

#endif // TEACHER_H

teacher.cpp:

#include "teacher.h"
#include<QDebug>
Teacher::Teacher(){}
void  Teacher::What_Answer()
{
    qDebug()<<"what is the Answer? Students."<<endl;
    emit tech_signal();
}
void Teacher::Answer_stu_Question()
{
    qDebug()<<"I don't know too."<<endl;
}

main.cpp:

#include<QCoreApplication>
#include "student.h"
#include "teacher.h"
#include<QDebug>
int main(int argc,char **argv)
{
    QCoreApplication app(argc,argv);
    Teacher t;
    Student s;
    QObject::connect(&t,SIGNAL(tech_signal()),&s,SLOT( Answer_Queston()));
     QObject::connect(&s,SIGNAL(stu_signal()),&t,SLOT( Answer_stu_Question()));
    t.What_Answer();
   s.Ask_Tech_Question();
    return app.exec();
}

输出:

原文地址:https://www.cnblogs.com/SunShine-gzw/p/13259873.html