前言:
在上一篇提到了回调函数,但是在使用过程中,有些小伙伴还是有点不太理解,今天再来一篇,直接上代码,对于小伙伴们来说是最好的了。
这里的例子是用QT的mainwindow工程写的,直接拷贝粘贴就可以,也可以直接下载工程包。
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
typedef int(*lpFunc)(int,int);
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void setCallback(lpFunc);
private slots:
void onTimeOut();
private:
Ui::MainWindow *ui;
lpFunc m_lpFunc;
QTimer* m_timer;
int m_cnt=0;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
int add(int a,int b);
int add(int a,int b)
{
qDebug() << "a+b== " << a << b;
return 0;
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setCallback(&add);
m_timer = new QTimer(this);
connect(m_timer,SIGNAL(timeout()),this,SLOT(onTimeOut()));
m_timer->start(100);
}
void MainWindow::onTimeOut()
{
m_cnt++;
if(m_cnt%10 == 0)
{
m_lpFunc(m_cnt,m_cnt+1);
}
}
MainWindow::~MainWindow()
{
m_timer->stop();
delete ui;
}
void MainWindow::setCallback(lpFunc a_lpFunc)
{
m_lpFunc = a_lpFunc;
}
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}