1、MyWidget
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
signals:
public slots:
void slotThreadQuit();
};
#endif // MYWIDGET_H
2、Mywidget.cpp
#include "MyWidget.h"
#include <QPushButton>
#include "Worker.h"
#include <QHBoxLayout>
#include <QDebug>
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
QHBoxLayout* lay = new QHBoxLayout(this);
Worker* work = new Worker;
QPushButton* button = new QPushButton("StarWork",this);
connect(button,SIGNAL(clicked()),work,SLOT(slotDoJob()));
lay->addWidget(button);
button = new QPushButton("StopWork",this);
//线程退出
connect(button,SIGNAL(clicked()),work->_thread,SLOT(quit()));
lay->addWidget(button);
connect(work->_thread,SIGNAL(finished()),this,SLOT(slotThreadQuit()));
}
void MyWidget::slotThreadQuit()
{
qDebug()<<"slotThreadQuit is called";
}
3、Worker.h
#ifndef WORKER_H
#define WORKER_H
#include <QObject>
#include <QThread>
//繁重的工作
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0);
QThread* _thread;
signals:
public slots:
void slotDoJob();
};
#endif // WORKER_H
4、Worker.cpp
#include "Worker.h"
#include <QThread>
#include <QDebug>
#include <QMessageBox>
/*某个对象属于线程,线程托管*/
Worker::Worker(QObject *parent) :
QObject(parent)
{
_thread = new QThread;
//该对象被_thread接管
this->moveToThread(_thread);
_thread->start();
//connect(_thread,SIGNAL(started()),);
//线程退出时,销毁对象线程
connect(_thread,SIGNAL(finished()),this,SLOT(deleteLater()));
}
void Worker::slotDoJob()
{
//线程不支持GUI
//QMessageBox::warning(NULL,"111","222");
int i = 0;
qDebug()<<"Hello slotDoJob";
#if 0
for(;;)
{
++i;
QThread::sleep(1);
qDebug()<< i;
}
#endif
}
5、main.cpp
#include <QApplication>
#include "MyWidget.h"
#include <QThread>
#include <QDebug>
#if 0
class MyThread: public QThread
{
void run()
{
qDebug() << "child Thread id:" << QThread::currentThreadId();
QThread::sleep(4);
QThread::msleep(1000);
}
};
#endif
//1、线程不能使用GUI
int main(int argc,char* argv[])
{
QApplication app(argc,argv);
MyWidget w;
w.show();
#if 0
MyThread thread;
QObject::connect(&thread,SIGNAL(finished()),&w,SLOT(close()));
thread.start();
#endif
qDebug() << "main thread id:"<< QThread::currentThreadId();
return app.exec();
}