一、创建自定义信号与槽函数
新建一个项目,名称:02_SignalsAndSlot(可自定义)
背景:下课后,老师触发一个信号->饿了,学生响应信号->请客吃饭
增加两个类:Teacher、Student(新建C++ Class类)
1、创建Teacher类,继承自QObject,定义信号(signals)为饿了Hungry
-
#ifndef TEACHER_H
-
#define TEACHER_H
-
-
#include <QObject>
-
#include <QDebug>
-
-
class Teacher :
public QObject
-
{
-
Q_OBJECT
-
public:
-
explicit Teacher(QObject *parent = nullptr);
-
-
signals:
-
void Hungry();
//信号不需要实现
-
public slots:
-
};
-
-
#endif // TEACHER_H
-
//.cpp文件不需要做任何修改
-
#include "teacher.h"
-
-
Teacher::Teacher(QObject *parent) : QObject(parent)
-
{
-
-
}
2、同样步骤创建Student类继承自QObject,定义slots槽函数为请客Treat()
-
#ifndef STUDENT_H
-
#define STUDENT_H
-
-
#include <QObject>
-
-
class Student :
public QObject
-
{
-
Q_OBJECT
-
public:
-
explicit Student(QObject *parent = nullptr);
-
-
signals:
-
-
public slots:
-
void Treat();
-
};
-
-
#endif // STUDENT_H
在.cpp中实现槽函数
-
#include "student.h"
-
#include <QDebug>
-
-
Student::Student(QObject *parent) : QObject(parent)
-
{
-
-
}
-
void Student::Treat()
-
{
-
qDebug(
"请老师吃饭");
-
}
二、使用信号与槽
1、MainWindow.h头文件中导入#include "teacher.h",#include "student.h",并声明指针变量和和一个出发函数classisover()
-
#ifndef MAINWINDOW_H
-
#define MAINWINDOW_H
-
#include "teacher.h"
-
#include "student.h"
-
#include <QMainWindow>
-
-
namespace Ui {
-
class MainWindow;
-
}
-
-
class MainWindow :
public QMainWindow
-
{
-
Q_OBJECT
-
-
public:
-
explicit MainWindow(QWidget *parent = nullptr);
-
~MainWindow();
-
-
private:
-
Ui::MainWindow *ui;
-
Teacher * tc;
-
Student * st;
-
void classIsOver();
-
};
-
-
#endif // MAINWINDOW_H
2、MainWindow.cpp中使用emit关键字触发信号,connect(sender,SIGNAL(signal()),receiver,SLOT(slot()));connect方法就是把发送者、信号、接受者和槽存储起来,供后续执行信号时查找
-
#include "mainwindow.h"
-
#include "ui_mainwindow.h"
-
MainWindow::MainWindow(QWidget *parent) :
-
QMainWindow(parent),
-
ui(
new Ui::MainWindow)
-
{
-
ui->setupUi(
this);
-
//创建一个老师对象
-
this->tc =
new Teacher(
this);
-
//创建一个学生对象
-
this->st =
new Student(
this);
-
-
//老师饿了 学生请客连接==
-
connect(tc, &Teacher::Hungry, st, &Student::Treat);
-
//调用下课函数
-
classIsOver();
-
}
-
-
MainWindow::~MainWindow()
-
{
-
delete ui;
-
}
-
-
void MainWindow::classIsOver()
-
{
-
emit tc->Hungry();
//成功触发 使用emit关键字
-
}
三、运行
转载:https://blog.csdn.net/fsdad/article/details/117256098
查看评论