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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用