1. 回调函数机制,可以提前注册相关事件,进行回调
其实质就是函数指针的操作,通常采用C语言定义函数,C++也可以用 using 定义函数指针。
对于函数 void function(char*,int)
C语言这样定义: typedef void(*func)(char*,int);
C++ 函数定义:using func = void(*)(char*,int);
具体见一下例子:
call.h
#ifndef CALL_H
#define CALL_H
#include <QObject>
#include <QTimer>
#include <QPoint>
#include "windows.h"
class call : public QObject
{
Q_OBJECT
public:
explicit call(QObject *parent = nullptr);
void setCallbackFunc(void(*func)(QPoint point));
private:
QTimer *timer;
void(*m_callbackFunc)(QPoint point);
private slots:
void timerout();
};
#endif // CALL_H
call.cpp
#include "call.h"
call::call(QObject *parent) : QObject(parent)
{
timer = new QTimer;
connect(timer,&QTimer::timeout,this,&call::timerout);
timer->start(1000);
}
void call::setCallbackFunc(void (*func)(QPoint))
{
m_callbackFunc = func;
}
void call::timerout()
{
//定时器每秒获取一次当前鼠标坐标
POINT point;
GetCursorPos(&point);
QPoint poi;
poi.setX(point.x);
poi.setY(point.y);
m_callbackFunc(poi);
}
使用call模块,并监听回调函数
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QDebug>
#include "call.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
static void getPoint(QPoint point);//回调函数监听函数
call *m_call;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
m_call = new call(this);
m_call->setCallbackFunc(getPoint);
}
Widget::~Widget()
{
delete ui;
}
void Widget::getPoint(QPoint point)
{
qDebug()<<point;
}
运行后每秒打印一次当前鼠标位置