当前位置:网站首页>QT signal and slot mechanism (detailed)
QT signal and slot mechanism (detailed)
2022-07-28 12:56:00 【Bitongo】
List of articles
One 、 What is a signal slot ?
Signal slot yes Qt One of the mechanisms that the framework is proud of . The so-called signal slot , It's actually the observer model . When something happens , such as , The button detects that it has been clicked , It will send a signal (signal). There is no purpose for this kind of sending out , Like radio . If someone is interested in this signal , It will use connections (connect) function , intend , Combine the signal you want to process with your own function ( Called slot (slot)) Binding to handle this signal . in other words , When the signal comes out , The connected slot function will be called back automatically . It's like the observer model : When something interesting happens , An operation is automatically triggered .
Two 、 Usage of signal slot
connect() The most commonly used general form of a function :
connect(sender, signal, receiver, slot);
Parameter interpretation :
sender: The object of the signal
signal: Sending signals from objects
receiver: The object receiving the signal
slot: The function that the receiving object needs to call after receiving the signal ( Slot function )
The signals of the system are as follows
void clicked(bool checked = false)
void pressed()
void released()
void toggled(bool checked )
signals inherited from Qwidget
signals inherited from Q0bject
3、 ... and 、 Custom signals and slots
Use connect() It allows us to connect the signals and slots provided by the system . however ,Qt The signal slot mechanism of the system is not just to use the part provided by the system , We will also be allowed to design our own signals and slots .
Let's take a look at using Qt The signal slot :
- First, define a student class and a teacher class :
A signal is declared in the teacher class I'm hungry hungry
signals:
void hungury();
- The student class declares that Treat treat
public slots:
void treat();
- Declare a public method in the window , The call to this method will trigger this signal , And the response slot function students treat
void MyWidget::ClassIsOver()
{
// Sending signal
emit teacher->hungury();
}
- The students responded to the slot function , And print information
// Custom slot function Realization
void Student::eat()
{
qDebug() << " It's time to have a meal. !";
}
- Connect the signal slot in the window
teacher = new Teacher(this);
student = new Student(this);
connect(teacher,&Teacher::hungury,student,&Student::treat);
And call the end function , The test prints out “ It's time to have a meal. ”
- Custom signals hungry With parameters , Need to provide overloaded custom signals and Custom slot
void hungury(QString name); Custom signal
void treat(QString name ); Custom slot
- But because there are two custom signals with duplicate names and custom slots , Direct connection will report an error , So you need to use the function pointer to point to the function address , And then we're making connections
void (Teacher:: * teacherSingal)(QString) = &Teacher::hungury;
void (Student:: * studentSlot)(QString) = &Student::treat;
connect(teacher,teacherSingal,student,studentSlot);
Notes for custom signal slot :
- Both sender and receiver need to be QObject Subclasses of ( Of course , Slot functions are global functions 、Lambda Except when there is no receiver for expressions, etc );
- The return value of the signal and slot functions is void
- Signals only need to declare , There is no need to achieve
- Slot functions need to be declared and implemented
- Slot functions are ordinary member functions , As a member function , Will receive public、private、protected Influence ;
- Use emit Send a signal in the right place ;
- Use connect() The function connects the signal to the slot .
- Any member function 、static function 、 Global functions and Lambda Expressions can be used as slot functions
- Signal slot requires that the parameters of signal and slot are consistent , Consistency , Is the parameter type consistent .
- If the parameters of the signal and the slot are inconsistent , The permissible situation is , The slot function can have fewer parameters than the signal , even so , The order of the parameters of the slot function must also be consistent with the previous ones of the signal . This is because , You can choose to ignore the data from the signal in the slot function ( That is, the parameters of the slot function are less than those of the signal ).
Four 、 Complete routine
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:
// In the early Qt edition , It has to be written public slots Next , The advanced version can be written to public Or overall
// Return value void, Need statement , It also needs to be realized
// There can be parameters , Overloading can happen
void treat(); // treat The meaning of treat
void treat(QString foodName);
};
#endif // STUDENT_H
teacher.h
#ifndef TEACHER_H
#define TEACHER_H
#include <QObject>
class Teacher : public QObject
{
Q_OBJECT
public:
explicit Teacher(QObject *parent = nullptr);
signals:
// Custom signal , writes signals Next
// The return value is void Just declare , There is no need to achieve
// There can be parameters , Can overload
void hungry();
void hungry(QString foodName);
public slots:
};
#endif // TEACHER_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include"teacher.h"
#include"student.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
Teacher * zt;
Student * st;
void classIsOver();
};
#endif // WIDGET_H
student.cpp
#include "student.h"
#include<QDebug>
Student::Student(QObject *parent) : QObject(parent)
{
}
void Student::treat()
{
qDebug()<<" Invite the teacher to dinner ";
}
void Student::treat(QString foodName)
{
//qDebug()<<" Invite the teacher to dinner , The teacher wants to eat :"<<foodName ; // This line of code outputs “ Invite the teacher to dinner , The teacher wants to eat :" Kung Pao Chicken "”
// namely Kung Pao Chicken There will be quotation marks next to it
// If you want to remove quotation marks You need to change the QString type Turn into char * type Turn into QByteArray(.toUtf8()) Re turn char *(.data())
qDebug()<<" Invite the teacher to dinner , The teacher wants to eat :"<<foodName.toUtf8().data(); // So there are no quotation marks
}
teacher.cpp
#include "teacher.h"
Teacher::Teacher(QObject *parent) : QObject(parent)
{
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include<QPushButton>
#include<QDebug>
//Teacher class The teacher class
//Student class Students
// After class , The teacher will trigger a signal , I'm hungry , Student corresponding signal , Dinner
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
// Create a teacher object
this->zt=new Teacher(this);
// Create a student object
this->st=new Student(this);
// // The teacher is hungry The connection of students' dinner
// connect(zt,&Teacher::hungry,st,&Student::treat);
// // First use connect Connect teacher and student signals , Then call the end function Make the teacher send a trigger signal
// // Call the end of class function
// classIsOver();
// Connect the signal and slot with parameters
// The pointer -> Address A function pointer -> Function address
// A function pointer : Function return value type (* Pointer variable name )( Function parameter list )
void(Teacher::*teacherSignal)(QString)=&Teacher::hungry;
void(Student::*studentSlot)(QString)=&Student::treat;
connect(zt,teacherSignal,st,studentSlot);
// classIsOver(); // This function causes the teacher to issue Hungry signal
// Click on a The button to finish class , Then trigger the end of class
QPushButton * btn1 =new QPushButton(" Class is over ",this);
this->resize(600,400); // Reset window size
// Click button Trigger the end of class
// connect(btn,&QPushButton::clicked,this,&Widget::classIsOver);
/* // Nonparametric signal and slot connection void(Teacher::*teacherSignal2)(void)=&Teacher::hungry; void(Student::*studentSlot2)(void)=&Student::treat; connect(zt,teacherSignal2,st,studentSlot2); // After the teacher sent out the hungry signal Students react */
// Signals connect signals
// connect(btn,&QPushButton::clicked,zt,teacherSignal2); // After clicking the button The teacher responded to the hungry signal
// Disconnect the signal
// disconnect(zt,teacherSignal2,st,studentSlot2); // This line of code can be disconnected The connection signal between teachers and classmates
// That is, after the teacher sends a hungry signal , Students will not react
//Lambda expression
/* QPushButton *btn3=new QPushButton("Over",this); btn3->move(100,0); [btn](){ //[] Only btn Below {} You can only recognize btn Related operations of btn->setText("aaaa"); // btn3->setText("bbbb"); // No recognition }(); // Add one at the end () Means to call this expression */
//mutable keyword Variables used to decorate value transfer , What's changed is the copy , Not ontology
/* QPushButton *mybtn=new QPushButton("one",this); QPushButton *mybtn2=new QPushButton("two",this); mybtn->move(100,0); mybtn2->move(100,100); int m=10; connect(mybtn,&QPushButton::clicked,this,[m]()mutable{m=100+10;qDebug()<<m;}); // Click on “one” Output m=110, That is, the copy value is modified connect(mybtn2,&QPushButton::clicked,this,[=](){qDebug()<<m;}); // Click on “two” Output m=10, namely m The ontology of has not been modified qDebug()<<m; */
// int ret=[]()->int{return 1000;}();
// qDebug()<<"ret = "<<ret;
// utilize Lambda expression Click the button close window The most commonly used expression is : [=](){}
QPushButton *btn2=new QPushButton(" close ",this);
btn2->move(100,0);
connect(btn2,&QPushButton::clicked,this,[=](){
// this->close(); // close window
emit zt->hungry(" Kung Pao Chicken "); // Click on “ close ” Button Trigger the signal that the teacher is hungry
});
}
void Widget::classIsOver()
{
// After class, function , After calling The signal that the teacher is hungry
//emit zt->hungry(); //emit Trigger custom signal keywords
emit zt->hungry(" Kung Pao Chicken ");
}
Widget::~Widget()
{
delete ui;
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
边栏推荐
- C structure use
- 1331. Array sequence number conversion: simple simulation question
- 快速读入
- Block reversal (summer vacation daily question 7)
- 输入字符串,内有数字和非字符数组,例如A123x456将其中连续的数字作为一个整数,依次存放到一个数组中,如123放到a[0],456放到a[1],并输出a这些数
- Zurich Federal Institute of technology | reference based image super resolution with deformable attention transformer (eccv2022))
- C语言项目中使用json
- GMT installation and use
- 西门子对接Leuze BPS_304i 笔记
- 利用依赖包直接实现分页、SQL语句
猜你喜欢
![[graduation design teaching] ultrasonic ranging system based on single chip microcomputer - Internet of things embedded stm32](/img/27/58fd175753b21dc21bd2d950cf5f15.png)
[graduation design teaching] ultrasonic ranging system based on single chip microcomputer - Internet of things embedded stm32

Fundamentals of machine learning - principal component analysis pca-16

Markdown concise grammar manual

GMT installation and use

Machine learning practice - decision tree-22

Leetcode: array

一台电脑上 多个项目公用一个 公私钥对拉取gerrit服务器代码

试用copilot过程中问题解决

云原生—运行时环境

Merge sort
随机推荐
scala 转换、过滤、分组、排序
大模型哪家强?OpenBMB发布BMList给你答案!
Leetcode94. Middle order traversal of binary trees
区块反转(暑假每日一题 7)
JSP自定义标签之自定义分页标签02
Aopmai biological has passed the registration: the half year revenue is 147million, and Guoshou Chengda and Dachen are shareholders
【Base】优化性能到底在优化啥?
20220728 common methods of object class
Machine learning practice - integrated learning-23
[graduation design] heart rate detection system based on single chip microcomputer - STM32 embedded Internet of things
Monotonic stack
leetcode 1518. 换酒问题
Machine learning practice - neural network-21
Unity loads GLB model
Which big model is better? Openbmb releases bmlist to give you the answer!
What if the win11 folder cannot be opened
Siemens docking Leuze BPS_ 304i notes
MySQL is always installed unsuccessfully. Just do it like this
Custom paging tag 02 of JSP custom tag
mysql limit 分页优化