qt 中回調函數的實現


在QT中回調函數主要可以實現多態性,通過回調函數可以動態處理一些操作。在多線程中,當同時需要處理多個事務的時候,顯然你會去創建多個線程類然后實例化,這顯然會增加開發工作,當我們在線程類中加入一個回調函數,在run()函數調用這個回調函數,顯然可以降低線程的耦合性,提高開發效率,在實例化這個線程時,傳遞實例化的回調函數到這線程中,這樣就避免了線程類的重復創建。回調函數的實現主要有兩種:

首先定義function的如下函數

#include <functional>

std::function<void(const QString&)> lambdaFunction

第一種:lambda表達式

我們可以通過定義如下表達式

lambdaFunction = [](const QString &s)
{
    qDebug()<<"lambda :"<<s;
};

然后將lambdaFunction這個回調函數賦值給線程的回調函數中。

第二種:直接定義實現函數:

void directPrint(const QString &msg)
{
    qDebug()<<"direct print:"<<msg;
}

lambdaFunction = directPrint;

同樣的方法傳入線程

具體線程實現如下:

#ifndef MYCLOCKS_H
#define MYCLOCKS_H
#include <QThread>
#include <functional>
class myClocks: public QThread
{
  Q_OBJECT
  public:
    myClocks(QObject *parent=0);
  public:
    void setCallback(void(*func)(QString));

  protected:
    virtual void run();

private:
    std::function<void(QString)> m_func;
signals:
    void threadSignal(QString s);
};
    QString callBackInstance();

#endif // MYCLOCKS_H
#include "myclocks.h"
#include <QDebug>
#include"qdatetime.h"
#include"qstring.h"

QString callBackInstance()
{
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("yyyy年MM月dd日 hh:mm:ss");
    return current_date;
}
myClocks::myClocks(QObject *parent)
: QThread(parent)
{
  m_func = nullptr;
}

void myClocks::run()
{
  if (m_func != nullptr)
  m_func();
  auto func = [&](){callBackInstance();};
  setCallback(func);
  while(1)
  {
    QString str=m_func();
    emit threadSignal( str);
    sleep(1);
  }
}

void myClocks::setCallback(std::function<void(QString)> func)
{
  m_func = func;
}
 
————————————————
版權聲明:本文為CSDN博主「fsfsfsdfsdfdr」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/fsfsfsdfsdfdr/article/details/83268743


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM