[Qt]自定义信号槽(1)
信号槽添加方法
QObject::connect(const QObject *sender,
const char *signal,
const QObject *receiver,
const char *method,
Qt::ConnectionType type = Qt::AutoConnection)
参数说明:
sender:信号发出者
signal:发送信号
receiver:信号接收者
method:信号处理者
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(); }; #endif // TEACHER_H
2、新增信号槽关联对象
#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(); }; #endif // TEACHER_H
实现方法
#include "student.h" #include "QDebug" student::student(QObject *parent) : QObject(parent) { } void student::eat(){ qDebug() << "吃饭去"; }
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); this->start(); } void Widget::start(){ //触发信号槽 emit this->teh->hungry(); } Widget::~Widget() { }
运行结果: