信号和槽的定义和使用
信号和槽的相关概念:
用信号和槽,实现一个功能:
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
:
void treat();
void treat(QString foodName
);
};
#endif
student类的.cpp代码
#include "student.h"
#include <QDebug>
student
::student(QObject
*parent
) : QObject(parent
)
{
}
void student
::treat(){
qDebug() << "老师吃饭了";
}
void student
::treat(QString foodName
){
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
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
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 th
->hungry();
emit th
->hungry(QString
("回锅肉"));
}
myWidget
::~myWidget()
{
}
转载请注明原文地址: https://yun.8miu.com/read-61542.html