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
相关文章
- Qt中QMap键值对基本用法(键值对)
- C/C++ Qt Tree与Tab组件实现分页菜单
- 分享一个收集Qt库的网站
- 调度Linux Qt环境下的进程调度优化(linuxqt进程)
- Qt 实现 Linux 串口通信编程(qt串口linux)
- Linux Qt开发之旅 让软件实现自由自在(linuxqtso)
- 管理掌握Linux Qt系统管理技能,实现无忧运作(linuxqt系统)
- Qt操作MYSQL:只需几步就能实现(qt操作mysql)
- Linux下高效安装Qt(linux下安装qt)
- Linux下Qt实现串口通信(linux下qt串口)
- qt和MySQL的结合,实现强大的数据库系统(qtmysql)
- QT实现对Oracle数据库的操作教程(qt操作oracle)
- 使用Qt实现MySQL数据库连接教程(qt连接mysql数据库)
- 提高数据处理效率:探究Qt与MySQL数据库的结合应用(qt与mysql数据库)
- QT开发MSSQL数据库技术实现(qt mssql)
- 在Linux下体验Qt的简便安装之旅(在linux下安装qt)
- MySQL和QT不配套使用,无法实现事务处理(mysql不支持qt事务)