QT自定义信号槽

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)
{

}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值