[Qt]自定义信号槽(2)
带参数的信号槽使用方法,重载的使用
1、新增信号槽发起类,teacher
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
class teacher : public QObject
{
Q_OBJECT
public:
teacher(QObject *parent = 0);
signals:
//自定义信号槽
//返回void
//可以有参数,无参数 重载
void hungry();
//重载方法 传入吃的东西名称
void hungry(QString name);
};
#endif // TEACHER_H2、新增信号槽关联对象
#ifndef STUDENT_H
#define STUDENT_H
#include <QObject>
class student: public QObject
{
// Q_OBJECT
public:
student(QObject *parent = 0);
public slots:
//早起QT必须写的此处,高级的可以在public下
//返回值void, 声明+实现
//可以有参数,无参数 重载
void eat();
//重载函数 吃啥
void eat(QString name);
};
#endif // STUDENT_H实现方法
#include "student.h"
#include "QDebug"
student::student(QObject *parent)
: QObject(parent)
{
}
void student::eat(){
qDebug() << "吃饭去";
}
void student::eat(QString name){
qDebug() << "吃["+name+"]去";
}3、主界面中关联信号槽
#include "widget.h"
#include "teacher.h"
#include "student.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
//初始化
this->stu =new student;
this->teh = new teacher;
//关联信号槽
//connect(teh,&teacher::hungry,stu,&student::eat);
//关联带参数的信号槽
//函数指针->地址
void(teacher::*teacherSingler)(QString) = &teacher::hungry;
void(student::*studentSlot)(QString) = &student::eat;
connect(teh,teacherSingler,stu,studentSlot);
this->start();
}
void Widget::start(){
//触发信号槽
//emit this->teh->hungry();
emit this->teh->hungry("肉末茄子");
}
Widget::~Widget()
{
}运行结果:
