按钮->点击->窗口->关闭窗口
connect(信号的发送者,发送具体信号,信号的接收者,信号的处理);
信号处理函数称为槽
信号槽的优点,松散耦合,信号发送端和接收端本身是没有关联的,通过connect连接将两端耦合在一起
//点击按钮,关闭当前窗口 connect(myBtn, &QPushButton::clicked, this, &QWidget::close);
自定义信号和槽
teacher.h
#ifndef TEACHER_H #define TEACHER_H #include <QObject> class Teacher : public QObject { Q_OBJECT public: explicit Teacher(QObject *parent = nullptr); //自定义信号写到signals下 //返回值类型为void,只需要声明,不需要实现 //可以有参数,可以重载 signals: void hungry(); }; #endif // TEACHER_H
student.h
#ifndef STUDENT_H #define STUDENT_H #include <QObject> class Student : public QObject { Q_OBJECT public: explicit Student(QObject *parent = nullptr); //可以写到public下 //返回值类型为void,需要声明,也需要实现 //可以有参数,也可以重载 void please(); signals: }; #endif // STUDENT_H
student.cpp
#include "student.h" #include <iostream> Student::Student(QObject *parent) : QObject(parent) { } void Student::please() { std::cout << "please teacher eat dinner" << std::endl; }
mywidget.h
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> #include "teacher.h" #include "student.h" class myWidget : public QWidget { Q_OBJECT public: myWidget(QWidget *parent = nullptr); Teacher *t = new Teacher(this); Student *s = new Student(this); ~myWidget(); }; #endif // MYWIDGET_H
mywidegt.cpp
#include "mywidget.h" myWidget::myWidget(QWidget *parent) : QWidget(parent) { connect(this->t, &Teacher::hungry, this->s, &Student::please); //建立信号与槽的连接 emit(this->t->hungry()); //发射信号 } myWidget::~myWidget() { }
标签:qt,parent,信号,Student,myWidget,include,public From: https://www.cnblogs.com/WTSRUVF/p/16808368.html