信号和槽的定义和使用
信号和槽的相关概念:
用信号和槽,实现一个功能:
1.定义teacher和student两个类(继承Qobject);
2.teacher类发送信号hungry(),student类接受信号,用槽函数treat()响应;
student类的.h代码
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
class student : public QObject
{
Q_OBJECT
public:
explicit student(QObject *parent = nullptr);
signals:
public slots:
//请客的槽函数,用来响应teacher发来的hurry信号
//信号和槽函数的参数类型必须一一对应
void treat();
void treat(QString foodName);
};
#endif // STUDENT_H
student类的.cpp代码
#include "student.h"
#include <QDebug>
student::student(QObject *parent) : QObject(parent)
{
}
void student::treat(){
qDebug() << "老师吃饭了";
}
void student::treat(QString foodName){
//将QString转换为char *p
qDebug() << "老师要吃:" << foodName.toUtf8().data();
}
teacher类的.h代码
#ifndef TEACHER2_H
#define TEACHER2_H
#include <QObject>
class teacher2 : public QObject
{
Q_OBJECT
public:
explicit teacher2(QObject *parent = nullptr);
signals:
//定义的信号
//只需要声明,不需要实现
void hungry();
void hungry(QString foodName);
public slots:
};
#endif // TEACHER2_H
teacher类的.cpp文件
#include "teacher2.h"
teacher2::teacher2(QObject *parent) : QObject(parent)
{
}
widget.h代码
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include "student.h"
#include "teacher2.h"
class myWidget : public QWidget
{
Q_OBJECT
public:
myWidget(QWidget *parent = 0);
~myWidget();
void class_over();
teacher2 * th;
student *st;
};
#endif // MYWIDGET_H
widget.cpp代码
#include "mywidget.h"
#include<QPushButton>
#include <QDebug>
myWidget::myWidget(QWidget *parent)
: QWidget(parent)
{
th = new teacher2(this);
st = new student(this);
//连接信号和槽,不带参数的
void (teacher2:: * teacher_signal1)(void) = &teacher2::hungry;
void (student:: * student_slot1)(void) = &student::treat;
connect(th, teacher_signal1, st, student_slot1);
//信号连接信号
QPushButton* btn = new QPushButton;
btn->setParent(this);
btn->setText("下课了");
connect(btn, &QPushButton::clicked, th, teacher_signal1);
class_over();
//连接带参数的信号和槽函数
void (teacher2:: *teacher_signal2)(QString) = &teacher2::hungry;
void (student:: *student_slot2)(QString) = &student::treat;
QPushButton* btn2 = new QPushButton("回锅肉");
btn2->setParent(this);
btn2->move(100,100);
connect(th, teacher_signal2,st, student_slot2);
connect(btn2, &QPushButton::clicked, th, teacher_signal2);
}
void myWidget::class_over(){
//发送自定义的信号
//用emit关键字,触发hungry()函数
emit th->hungry();
emit th->hungry(QString ("回锅肉"));
}
myWidget::~myWidget()
{
}