1.案例
由学校 发出 通知(signal) 学生接受 上课(slot)
ctrl+n 创建 student,school类
2.文件结构
①school.h
在类内,用signals关键字定义信号成员方法
#ifndef SCHOOL_H
#define SCHOOL_H
#include <QObject>
class School : public QObject
{
Q_OBJECT
public:
explicit School(QObject *parent = nullptr);
signals://Qt信号的关键字,只声明,不用定义
void sendMessages();
};
#endif // SCHOOL_H
②school.cpp
因Qt信号的关键字,只声明,不用定义,此例中并没有对其进行操作
#include "school.h"
School::School(QObject *parent) : QObject(parent)
{}
③student.h
槽函数:void comeBackToClass();//自定义槽
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
class Student : public QObject
{
Q_OBJECT
public:
explicit Student(QObject *parent = nullptr);
signals:
public slots:
// 声明后还需定义
void comeBackToClass();//自定义槽
};
#endif // STUDENT_H
④student.cpp
重写了槽函数
#include "student.h"
#include"QDebug"
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::comeBackToClass()
{
qDebug()<<"学生上课"<<endl;
}
⑤mainwindow.h
引入头文件,声明类,定义成员变量
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "school.h" //引入头文件
#include "student.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class Student; //声明类
class School;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
School *school;//声明成员变量
Student *student;
};
#endif // MAINWINDOW_H
⑥mainwindow.cpp
此处的this指针指向的是MainWindow对象,通过connect()函数将school,student对象所对应的信号与槽相关联,后通过emit关键字发出信号。
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);//
school = new School(); // 实例化对象
student = new Student();
connect(school,SIGNAL(sendMessages()),student,SLOT(comeBackToClass()));
emit school->sendMessages(); //emit发出信号关键字
}
MainWindow::~MainWindow()
{
delete ui;
}