qfedu-qt-level/qtdemo01/widget3.cpp

67 lines
2.0 KiB
C++
Raw Normal View History

2023-08-07 19:24:59 +08:00
#include "widget3.h"
Widget3::Widget3(QWidget *parent) : QWidget(parent)
{
setWindowTitle("自定义信号和槽");
resize(800,640);
stu = new Student();
stu->setParent(this);
techr = new Teacher(this);
// 绑定无参信号
void(Student:: *sleep1)() = &Student::sleep;
void(Teacher:: *wakeup1)() = &Teacher::wake_up;
connect(stu,sleep1,techr,wakeup1);
// 绑定有参的信号和槽函数
void(Student:: *sleep2)(const QString &,int n) = &Student::sleep;
void(Teacher:: *wakeup2)(const QString &) = &Teacher::wake_up;
connect(stu,sleep2,techr,wakeup2);
// 手动发送一个信号
// emit stu->sleep();
// 点击按钮发送学生睡觉的信号
QPushButton *btn = new QPushButton("我睡会",this);
btn->resize(120,50);
btn->move(20,20);
QPushButton *btn2 = new QPushButton("再睡会",this);
btn2->resize(120,50);
btn2->move(20,90);
edit = new QLineEdit(this);
edit->resize(300,50);
edit->move(20,160);
// 将一个信号绑定到另一个信号上,即发送另一个信号
// connect(btn,&QPushButton::clicked,stu,&Student::sleep);
// connect(btn,&QPushButton::clicked,this,&Widget3::to_sleep);
connect(btn, SIGNAL(clicked()) ,this,SLOT(to_sleep())); // QT4 的信号槽写法
// connect(btn2,&QPushButton::clicked,this,&Widget3::to_sleep2);
// Lambda表达式匿名函数
// connect(btn,&QPushButton::clicked,[&](){
// emit stu->sleep();
// void(Student:: *sleep1)() = &Student::sleep;
// void(Teacher:: *wakeup1)() = &Teacher::wake_up;
// disconnect(stu,sleep1,techr,wakeup1);
// });
connect(btn2,&QPushButton::clicked,[&](){
const QString msg = edit->text();
emit stu->sleep(msg,2);
});
}
void Widget3::to_sleep()
{
emit stu->sleep(); // 发送一个睡觉的信号
}
void Widget3::to_sleep2()
{
const QString &msg = edit->text();
emit stu->sleep(msg,2);
}