QT中使用回调函数(二)

前言:

    在上一篇提到了回调函数,但是在使用过程中,有些小伙伴还是有点不太理解,今天再来一篇,直接上代码,对于小伙伴们来说是最好的了。

这里的例子是用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();
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值