- 自定义信号
1.写到signal下
2.返回void
3.需要声明,不需要实现
4.可以有参数,可以重载 - 自定义槽函数
1.返回void
2.需要声明,也需要实现
3.可以有参数,可以重载
4.写到pulic slot下或者pulic或者全局函数 - 触发自定义的信号
1.emit 自定义信号 - 案例:下课后,老师触发饿了信号,学生响应信号,请客吃饭。
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
signals:
//信号函数,老师饿了,只声明不实现
void hungry();
};
#endif // TEACHER_H
#include "teacher.h"
Teacher::Teacher(QObject *parent)
: QObject{parent}
{}
#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
#include "student.h"
#include<QDebug>
Student::Student(QObject *parent)
: QObject{parent}
{}
void Student::treat()
{
qDebug()<<"老师饿了,学生请客吃饭";
}
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void classOver();
private:
Ui::Widget *ui;
Teacher*t;
Student*s;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->t=new Teacher(this);
this->s=new Student(this);
//先链接信号与槽
connect(t,&Teacher::hungry,s,&Student::treat);
//发出信号
classOver();
}
//下课函数,封装激发信号的指令
void Widget::classOver()
{
qDebug()<<"下课了!";
emit t->hungry(); //激发信号
}
Widget::~Widget()
{
delete ui;
}
标签:Widget,信号,parent,QObject,Student,include,Teacher,自定义
From: https://www.cnblogs.com/qinbaoyang/p/18318087