自定义信号槽

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;
}

3.运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值