[QT] Implementation of callback function

The callback function is a function you write and let the pre-written system call it. The function you call the system is a direct adjustment. Let the system call your function, which is the callback.

A makes B do things, depending on the granularity, it can be understood as A function calls B function, or A class uses B class, or A component uses B component, etc. Anyway, A tells B to do something. When B does this, the information he needs is not enough, but A has. It needs A to pass it in from the outside, or B is doing it and then applying to the outside. For B, one is to passively obtain information, and the other is to actively obtain information. Some people give these two methods a term called information push (push) and information pull (pull).

1、callback.h

#ifndef CALLBACK_H
#define CALLBACK_H

/*A 让 B 排序,B 会做排序,但排序需要知道哪个比哪个大,
 * 这点 B 自己不知道,就需要 A 告诉它。而判断大小本身是某种行为,
 * 既然 C 语言中不可以传进第一值的函数,就设计成传递第二值的函数指针,
 * 这个函数指针是 A 传向 B 的信息,用于描述判断大小这种行为。
 * 这里本来 A 调用 B 的,结果 B 又调用了 A 告诉它的信息,也就是 callback
*/

#include <QWidget>

typedef double(*cbFunc)(double,double);      //函数指针

class CallBack : public QWidget
{
    
    
    Q_OBJECT
public:
    explicit CallBack(QWidget *parent = nullptr);

    void m_getData(cbFunc);       //调用回调函数

signals:

public slots:
};

#endif // CALLBACK_H

2、callback.cpp

#pragma execution_character_set("utf-8")
#include "callback.h"
#include <QDebug>

CallBack::CallBack(QWidget *parent) : QWidget(parent)
{
    
    

}

void CallBack::m_getData(cbFunc m_cbFunc)
{
    
    
    double i = m_cbFunc(3.6,5.7);
    qDebug() << "回调函数返回的数值: " << i;
}

3、widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include "callback.h"

class Widget : public QWidget
{
    
    
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

    CallBack m_callback;

    static double m_getPosition(double a, double b);

};

#endif // WIDGET_H

4、widget.cpp

#pragma execution_character_set("utf-8")
#include "widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    
    
    //通过传参的形式将该函数的地址传递给其他函数,然后在其他函数中通过函数指针调用该函数 --回调
    m_callback.m_getData(&m_getPosition);
}

Widget::~Widget()
{
    
    

}

double Widget::m_getPosition(double a, double b)
{
    
    
    qDebug() << "回调函数触发传入的数值是: " << a << b;
    return a+b;
}

5. Running result output

insert image description here

Guess you like

Origin blog.csdn.net/Cappuccino_jay/article/details/126162571