在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;
}
————————————————
版权声明:本文为****博主「fsfsfsdfsdfdr」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.****.net/fsfsfsdfsdfdr/article/details/83268743