main.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "teacher.h"
#include "student.h"
#include <QDebug>
#include <QPushButton>
//两个类 学生和老师
//老师发出饿了信号 学生响应信号 请客吃饭
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
zt = new Teacher();
st = new Student();
//链接老师和学生
//connect(zt,&Teacher::hungry,st,&Student::treat);
//有参数的信号和连接
//函数指针
void (Teacher:: *teacherSignal)(QString)= &Teacher::hungry;
void (Student:: *stSlot)(QString) = &Student::treat;
connect(zt,teacherSignal,st,stSlot);
//点击按钮下课
void (Teacher:: *noteacherSignal)()= &Teacher::hungry;
void (Student:: *nostSlot)() = &Student::treat;
QPushButton *btn = new QPushButton("下课",this);
connect(btn,&QPushButton::clicked,zt,noteacherSignal);
connect(btn,&QPushButton::clicked,this,&MainWindow::close);//一个信号可以链接多个槽,多个信号可以链接同一个槽
connect(zt,noteacherSignal,st,nostSlot);
//QT4版本,信号和槽写法
connect(zt,SIGNAL(hungry(QString)),st,SLOT(treat(QString)));
//不推荐QT4版本信号写法,不检查类型是否匹配
//有点:类型参数比较直观,发生重载也不用写函数指针
//不检测原因,SIGNAL和SLOT下,会把里面代码作为字符串处理。
//重置大小
resize(600, 400);
[=](){
btn->move(300,300);
}();
}
void MainWindow::classIsOver()
{
qDebug()<<"老师饿了";
emit zt->hungry("满汉全席");
emit zt->hungry();
}
MainWindow::~MainWindow()
{
delete ui;
}
student.cpp
#include "student.h"
#include <QDebug>
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::treat()
{
qDebug()<<"请客吃饭";
}
void Student::treat(QString foodName)
{
//qDebug()<<"请客吃饭"<<foodName;
//QString 转char*
qDebug()<<"请客吃饭"<<foodName.toUtf8().data();
}
teacher.cpp
#include "teacher.h"
Teacher::Teacher(QObject *parent) : QObject(parent)
{
}