zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Lab IGMP
    IGMP知识要点
    15、通过例子讲解逻辑地址转换为物理地址的基本过程
    14、一个程序从开始运行到结束的完整过程,你能说出来多少?
    13、进程状态的切换你知道多少?
    12、虚拟技术你了解吗?
    11、动态分区分配算法有哪几种?可以分别说说吗?
    线程池
    10、内存交换和覆盖有什么区别?
    9、如果系统中具有快表后,那么地址的转换过程变成什么样了?
  • 原文地址:https://www.cnblogs.com/bruce1992/p/14483648.html
Copyright © 2011-2022 走看看