qt线程动态回调被调类中的函数

来源:互联网 发布:改本地host变更域名 编辑:程序博客网 时间:2024/05/26 07:28

1.需求

要求封装一个qt线程能在不同类中调用,并能回调被调用类中的函数

2.解决

尝试多种方法,最终决定采用动态加载lamda表达式的方法解决

3.代码

catthread.h

#ifndef CATTHREAD_H#define CATTHREAD_H#include <QtCore/QThread>#include <functional>class catthread : public QThread{    Q_OBJECTpublic:    catthread(QObject *parent);    ~catthread(){}public:    void setCallback(std::function<void(void)> func); protected:    virtual void run();private:     std::function<void(void)> m_func;};#endif // CATTHREAD_H

catthread.cpp

#include "catthread.h"catthread::catthread(QObject *parent)    : QThread(parent){    m_func = nullptr;}void catthread::run(){    if (m_func != nullptr)        m_func();}void catthread::setCallback(std::function<void(void)> func){    m_func = func;}

gui中调用和回调

mythread.h

#ifndef MYTHREAD_H#define MYTHREAD_H#include <QtWidgets/QMainWindow>#include "ui_mythread.h"#include "catthread.h"class mythread : public QMainWindow{    Q_OBJECTpublic:    mythread(QWidget *parent = 0);    ~mythread();private slots:    void on_func1Button_clicked();    void on_func2Button_clicked();    void on_func3Button_clicked();    void thread_finish();public:    void func1();    void func2();    void func3();private:    Ui::mythreadClass ui;    catthread m_thread;public:    int m_nvalue;};#endif // MYTHREAD_H

mythread.cpp

#include "mythread.h"#include <QMessageBox>mythread::mythread(QWidget *parent)    : QMainWindow(parent),m_thread(parent){    ui.setupUi(this);    connect(&m_thread, SIGNAL(finished()), this, SLOT(thread_finish()));}mythread::~mythread(){}void mythread::func1(){    m_nvalue = 10;}void mythread::func2(){    m_nvalue = 20;}void mythread::func3(){    m_nvalue = 30;}void mythread::on_func1Button_clicked(){    if (!m_thread.isRunning())    {        auto func = [&](){func1();};        m_thread.setCallback(func);        m_thread.start();    }}void mythread::on_func2Button_clicked(){    if (!m_thread.isRunning())    {        auto func = [&](){func2();};        m_thread.setCallback(func);        m_thread.start();    }}void mythread::on_func3Button_clicked(){    if (!m_thread.isRunning())    {        auto func = [&](){func3();};        m_thread.setCallback(func);        m_thread.start();    }}void mythread::thread_finish(){    QString strMsg("");    strMsg = QString("%1").arg(m_nvalue);    QMessageBox::information(this, "msg", strMsg);}

main.cpp

#include "mythread.h"#include <QtWidgets/QApplication>int main(int argc, char *argv[]){    QApplication a(argc, argv);    mythread w;    w.show();    return a.exec();}

4.备注

1.在vs2010+win7+qt5.40下编译通过

2.传递不同类成员函数时可以采用lamda表达式实现

0 0