标签:qt线程封装
#ifndef CATTHREAD_H
#define CATTHREAD_H
#include <QtCore/QThread>
#include <functional>
class catthread : public QThread
{
Q_OBJECT
public:
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
#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;
}
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QtWidgets/QMainWindow>
#include "ui_mythread.h"
#include "catthread.h"
class mythread : public QMainWindow
{
Q_OBJECT
public:
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
#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);
}
#include "mythread.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
mythread w;
w.show();
return a.exec();
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:qt线程封装
原文地址:http://blog.csdn.net/zhang_ruiqiang/article/details/46972557